diff --git a/modules/game_prey_html/game_prey_html.lua b/modules/game_prey_html/game_prey_html.lua index 8188b5347d..754a3bcb4b 100644 --- a/modules/game_prey_html/game_prey_html.lua +++ b/modules/game_prey_html/game_prey_html.lua @@ -31,9 +31,11 @@ function PreyController:handleResources() local player = g_game.getLocalPlayer() if not player then return end + self.wildcards = player:getResourceBalance(ResourceTypes.PREY_WILDCARDS) + self.bankGold = player:getResourceBalance(ResourceTypes.BANK_BALANCE) + self.inventoryGold = player:getResourceBalance(ResourceTypes.GOLD_EQUIPPED) self.rawPlayerGold = player:getTotalMoney() or 0 self.playerGold = comma_value(self.rawPlayerGold) - self.wildcards = player:getResourceBalance(ResourceTypes.PREY_WILDCARDS) end function show() @@ -56,6 +58,7 @@ function toggle() end function PreyController:hide() + PreyController:handleResources() if PreyController.ui then PreyController:unloadHtml() end @@ -289,8 +292,10 @@ function onPreySelectionChangeMonster(slot, names, outfits, bonusType, bonusValu PreyController.preyData[slotId].percentFreeReroll = Helper.getProgress(timeUntilFreeReroll, Helper.freeRerollHours, Helper.freeRerollBarWidth) PreyController.preyData[slotId].timeUntilFreeReroll = timeleftTranslation(timeUntilFreeReroll) - PreyController.preyData[slotId].isFreeReroll = timeUntilFreeReroll == 0 - PreyController.preyData[slotId].disableFreeReroll = PreyController.rawRerollGoldPrice > PreyController.rawPlayerGold + local isFreeReroll = timeUntilFreeReroll == 0 + PreyController.preyData[slotId].isFreeReroll = isFreeReroll + PreyController.preyData[slotId].disableFreeReroll = PreyController.rawRerollGoldPrice > PreyController.rawPlayerGold and + not isFreeReroll end function onPreyInactive(slot, timeUntilFreeReroll, wildcards) @@ -576,8 +581,10 @@ function onPreySelection(slot, names, outfits, timeUntilFreeReroll, wildcards) PreyController.preyData[slotId].timeUntilFreeReroll = timeleftTranslation(timeUntilFreeReroll) PreyController.preyData[slotId].type = SLOT_STATE_SELECTION PreyController.preyData[slotId].monsterName = "Select your prey creature" - PreyController.preyData[slotId].isFreeReroll = timeUntilFreeReroll == 0 - PreyController.preyData[slotId].disableFreeReroll = PreyController.rawRerollGoldPrice > PreyController.rawPlayerGold + local isFreeReroll = timeUntilFreeReroll == 0 + PreyController.preyData[slotId].isFreeReroll = isFreeReroll + PreyController.preyData[slotId].disableFreeReroll = PreyController.rawRerollGoldPrice > PreyController.rawPlayerGold and + not isFreeReroll end function PreyController:onGameStart() @@ -689,9 +696,10 @@ function onPreyActive(slot, currentHolderName, currentHolderOutfit, bonusType, b PreyController.preyData[slotId].bonusType = bonusType PreyController.preyData[slotId].timeUntilFreeReroll = timeleftTranslation(rawTimeUntilFreeReroll) PreyController:handleResources() - PreyController.preyData[slotId].isFreeReroll = rawTimeUntilFreeReroll == 0 - PreyController.preyData[slotId].disableFreeReroll = PreyController.rawRerollGoldPrice > - PreyController.rawPlayerGold + local isFreeReroll = rawTimeUntilFreeReroll == 0 + PreyController.preyData[slotId].isFreeReroll = isFreeReroll + PreyController.preyData[slotId].disableFreeReroll = PreyController.rawRerollGoldPrice > PreyController.rawPlayerGold and + not isFreeReroll end function PreyController:onMouseWheel(slotId, hoveredIndex) diff --git a/modules/game_prey_html/prey_html.css b/modules/game_prey_html/prey_html.css index f1ed43cece..62f343aba5 100644 --- a/modules/game_prey_html/prey_html.css +++ b/modules/game_prey_html/prey_html.css @@ -397,7 +397,7 @@ .gold-container { --image-source: "/modules/game_prey_html/images/player-gold-bg.png"; - width: 200px; + width: 130px; height: 20px; text-align: center; align-items: center; diff --git a/modules/game_prey_html/prey_html.html b/modules/game_prey_html/prey_html.html index 2d205d6128..a1d84d4cd5 100644 --- a/modules/game_prey_html/prey_html.html +++ b/modules/game_prey_html/prey_html.html @@ -187,7 +187,7 @@ diff --git a/src/client/animator.cpp b/src/client/animator.cpp index 15b8e0ebe5..d92cf583e2 100644 --- a/src/client/animator.cpp +++ b/src/client/animator.cpp @@ -50,7 +50,7 @@ void Animator::unserialize(const int animationPhases, const FileStreamPtr& fin) m_loopCount = fin->get32(); m_startPhase = fin->get8(); - for (int i = 0; i < m_animationPhases; ++i) { + for (int i = 0; std::cmp_less(i, m_animationPhases); ++i) { int minimum = fin->getU32(); int maximum = fin->getU32(); m_phaseDurations.emplace_back(minimum, maximum); @@ -79,7 +79,7 @@ void Animator::serialize(const FileStreamPtr& fin) const void Animator::setPhase(const int phase) { - if (m_phase == phase) + if (std::cmp_equal(m_phase, phase)) return; if (!m_async) { @@ -91,7 +91,7 @@ void Animator::setPhase(const int phase) m_phase = 0; else if (phase == AnimPhaseRandom) m_phase = stdext::random_range(0, m_animationPhases); - else if (phase >= 0 && phase < m_animationPhases) + else if (phase >= 0 && std::cmp_less(phase, m_animationPhases)) m_phase = phase; else m_phase = getStartPhase(); @@ -107,14 +107,14 @@ int Animator::getPhase() const ticks_t ticks = g_clock.millis(); if (ticks != m_lastPhaseTicks && !m_isComplete) { const int elapsedTicks = static_cast(ticks - m_lastPhaseTicks); - if (elapsedTicks >= m_currentDuration) { + if (std::cmp_greater_equal(elapsedTicks, m_currentDuration)) { int phase; if (m_loopCount < 0) phase = getPingPongPhase(); else phase = getLoopPhase(); - if (m_phase != phase) { + if (std::cmp_not_equal(m_phase, phase)) { const int duration = getPhaseDuration(phase) - (elapsedTicks - m_currentDuration); if (duration < 0 && !m_async) { calculateSynchronous(); @@ -171,7 +171,7 @@ int Animator::getPingPongPhase() { int count = m_currentDirection == AnimDirForward ? 1 : -1; const int nextPhase = m_phase + count; - if (nextPhase < 0 || nextPhase >= m_animationPhases) { + if (nextPhase < 0 || std::cmp_greater_equal(nextPhase, m_animationPhases)) { m_currentDirection = m_currentDirection == AnimDirForward ? AnimDirBackward : AnimDirForward; count *= -1; } @@ -181,7 +181,7 @@ int Animator::getPingPongPhase() int Animator::getLoopPhase() { const int nextPhase = m_phase + 1; - if (nextPhase < m_animationPhases) + if (std::cmp_less(nextPhase, m_animationPhases)) return nextPhase; if (m_loopCount == 0) @@ -208,13 +208,13 @@ int Animator::getPhaseDuration(const int phase) const void Animator::calculateSynchronous() { int totalDuration = 0; - for (int i = 0; i < m_animationPhases; ++i) + for (int i = 0; std::cmp_less(i, m_animationPhases); ++i) totalDuration += getPhaseDuration(i); const ticks_t ticks = g_clock.millis(); const int elapsedTicks = static_cast(ticks % totalDuration); int totalTime = 0; - for (int i = 0; i < m_animationPhases; ++i) { + for (int i = 0; std::cmp_less(i, m_animationPhases); ++i) { const int duration = getPhaseDuration(i); if (elapsedTicks >= totalTime && elapsedTicks < totalTime + duration) { m_phase = i; diff --git a/src/client/attachedeffect.cpp b/src/client/attachedeffect.cpp index cacdf35dc1..92ec3eced3 100644 --- a/src/client/attachedeffect.cpp +++ b/src/client/attachedeffect.cpp @@ -85,7 +85,7 @@ void AttachedEffect::draw(const Point& dest, const bool isOnTop, const LightView return; const int animation = getCurrentAnimationPhase(); - if (m_loop > -1 && animation != m_lastAnimation) { + if (m_loop > -1 && std::cmp_not_equal(animation, m_lastAnimation)) { m_lastAnimation = animation; if (animation == 0 && --m_loop == 0) return; diff --git a/src/client/client.h b/src/client/client.h index 27d5cc2b8b..c8c9130aa5 100644 --- a/src/client/client.h +++ b/src/client/client.h @@ -38,7 +38,7 @@ class Client : public ApplicationDrawEvents void preLoad() override; void draw(DrawPoolType type) override; - bool canDraw(DrawPoolType type) const override; + [[nodiscard]] bool canDraw(DrawPoolType type) const override; bool isLoadingAsyncTexture() override; bool isUsingProtobuf() override; @@ -47,10 +47,10 @@ class Client : public ApplicationDrawEvents UIMapPtr getMapWidget() { return m_mapWidget; } - float getEffectAlpha() const { return m_effectAlpha; } + [[nodiscard]] float getEffectAlpha() const { return m_effectAlpha; } void setEffectAlpha(const float v) { m_effectAlpha = v; } - float getMissileAlpha() const { return m_missileAlpha; } + [[nodiscard]] float getMissileAlpha() const { return m_missileAlpha; } void setMissileAlpha(const float v) { m_missileAlpha = v; } private: diff --git a/src/client/const.h b/src/client/const.h index 5339da5549..db73ef7642 100644 --- a/src/client/const.h +++ b/src/client/const.h @@ -868,11 +868,11 @@ namespace Otc FIRST = KNIGHT, LAST = DRUID, }; - - enum PartyAnalyzerAction_t : uint8_t { + + enum PartyAnalyzerAction_t : uint8_t + { PARTYANALYZERACTION_RESET = 0, PARTYANALYZERACTION_PRICETYPE = 1, PARTYANALYZERACTION_PRICEVALUE = 2, }; - } diff --git a/src/client/container.cpp b/src/client/container.cpp index 40ba1f0b59..84068af201 100644 --- a/src/client/container.cpp +++ b/src/client/container.cpp @@ -21,11 +21,13 @@ */ #include "container.h" + #include "item.h" ItemPtr Container::getItem(const int slot) { - if (slot < 0 || slot >= static_cast(m_items.size())) + if (slot < 0 || std::cmp_greater_equal(slot, m_items.size()) + ) return nullptr; return m_items[slot]; } @@ -46,7 +48,7 @@ void Container::onAddItem(const ItemPtr& item, int slot) slot -= m_firstIndex; // indicates that there is a new item on next page - if (m_hasPages && slot > m_capacity) { + if (m_hasPages && std::cmp_greater(slot, m_capacity)) { callLuaField("onSizeChange", ++m_size); return; } @@ -58,7 +60,7 @@ void Container::onAddItem(const ItemPtr& item, int slot) m_items.insert(m_items.begin() + slot, item); ++m_size; - + updateItemsPositions(); callLuaField("onSizeChange", m_size); @@ -83,7 +85,8 @@ void Container::onAddItems(const std::vector& items) void Container::onUpdateItem(int slot, const ItemPtr& item) { slot -= m_firstIndex; - if (slot < 0 || slot >= static_cast(m_items.size())) { + if (slot < 0 || std::cmp_greater_equal(slot, m_items.size()) + ) { g_logger.traceError("slot not found"); return; } @@ -100,12 +103,14 @@ void Container::onRemoveItem(int slot, const ItemPtr& lastItem) slot -= m_firstIndex; // indicates that there has been deleted an item on next page - if (m_hasPages && slot >= static_cast(m_items.size())) { + if (m_hasPages && std::cmp_greater_equal(slot, m_items.size()) + ) { callLuaField("onSizeChange", --m_size); return; } - if (slot < 0 || slot >= static_cast(m_items.size())) { + if (slot < 0 || std::cmp_greater_equal(slot, m_items.size()) + ) { g_logger.traceError("slot not found"); return; } @@ -128,6 +133,6 @@ void Container::onRemoveItem(int slot, const ItemPtr& lastItem) void Container::updateItemsPositions() { - for (int slot = 0; slot < static_cast(m_items.size()); ++slot) + for (int slot = 0; std::cmp_less(slot, m_items.size()); ++slot) m_items[slot]->setPosition(getSlotPosition(slot)); -} +} \ No newline at end of file diff --git a/src/client/creature.cpp b/src/client/creature.cpp index 37bb5c4aa0..53a7cb914f 100644 --- a/src/client/creature.cpp +++ b/src/client/creature.cpp @@ -624,7 +624,7 @@ void Creature::updateWalkAnimation() const int footDelay = std::clamp(walkSpeed / footAnimDelay, minFootDelay, maxFootDelay); if (m_footTimer.ticksElapsed() >= footDelay) { - if (m_walkAnimationPhase == footAnimPhases) m_walkAnimationPhase = 1; + if (std::cmp_equal(m_walkAnimationPhase, footAnimPhases)) m_walkAnimationPhase = 1; else ++m_walkAnimationPhase; m_footTimer.restart(); @@ -916,7 +916,8 @@ void Creature::setIconsTexture(const std::string& filename, const Rect& clip, co m_icons->numberText.setAlign(Fw::AlignCenter); } - m_icons->atlasGroups.emplace_back(IconRenderData::AtlasIconGroup{ g_textures.getTexture(filename), clip, count }); + m_icons->atlasGroups.emplace_back(IconRenderData::AtlasIconGroup{ .texture = g_textures.getTexture(filename), + .clip = clip, .count = count }); } void Creature::setSkullTexture(const std::string& filename) { m_skullTexture = g_textures.getTexture(filename); } void Creature::setEmblemTexture(const std::string& filename) { m_emblemTexture = g_textures.getTexture(filename); } @@ -1014,7 +1015,7 @@ uint16_t Creature::getStepDuration(const bool ignoreDiagonal, const Otc::Directi if (groundSpeed == 0) groundSpeed = 150; - if (groundSpeed != m_stepCache.groundSpeed || m_speed != m_stepCache.speed) { + if (std::cmp_not_equal(groundSpeed, m_stepCache.groundSpeed) || m_speed != m_stepCache.speed) { m_stepCache.speed = m_speed; m_stepCache.groundSpeed = groundSpeed; diff --git a/src/client/creature.h b/src/client/creature.h index 89bdc3c780..31b46a59c6 100644 --- a/src/client/creature.h +++ b/src/client/creature.h @@ -244,7 +244,7 @@ minHeight, uint16_t walkDuration{ 0 }; uint16_t diagonalDuration{ 0 }; - uint16_t getDuration(const Otc::Direction dir) const { return Position::isDiagonal(dir) ? diagonalDuration : duration; } + [[nodiscard]] uint16_t getDuration(const Otc::Direction dir) const { return Position::isDiagonal(dir) ? diagonalDuration : duration; } }; struct IconRenderData diff --git a/src/client/effect.cpp b/src/client/effect.cpp index 1c6aadbaa5..1350591dc2 100644 --- a/src/client/effect.cpp +++ b/src/client/effect.cpp @@ -118,7 +118,7 @@ bool Effect::waitFor(const EffectPtr& effect) uint16_t minDuration = getIdleAnimator() ? getIdleAnimator()->getMinDuration() : g_gameConfig.getEffectTicksPerFrame(); minDuration = minDuration * std::max(getAnimationPhases() / 3, 1); - if (ticksElapsed <= minDuration) + if (std::cmp_less_equal(ticksElapsed, minDuration)) return false; const int duration = effect->m_duration / (g_app.mustOptimize() || g_app.isForcedEffectOptimization() ? 1.5 : 3); diff --git a/src/client/game.cpp b/src/client/game.cpp index ecc65c76ae..2b50f2f6fa 100644 --- a/src/client/game.cpp +++ b/src/client/game.cpp @@ -1531,7 +1531,7 @@ void Game::buyStoreOffer(const uint32_t offerId, const uint8_t action, const std if (!canPerformGameAction()) return; - m_protocolGame->sendBuyStoreOffer(offerId, action, name, type,location); + m_protocolGame->sendBuyStoreOffer(offerId, action, name, type, location); } void Game::requestTransactionHistory(const uint32_t page, const uint32_t entriesPerPage) @@ -1579,7 +1579,7 @@ void Game::sendRequestStoreOfferById(const uint32_t offerId, const uint8_t sortO if (!canPerformGameAction()) return; - m_protocolGame->sendRequestStoreOfferById(offerId, sortOrder , serviceType); + m_protocolGame->sendRequestStoreOfferById(offerId, sortOrder, serviceType); } void Game::sendRequestStoreSearch(const std::string_view searchText, const uint8_t sortOrder, const uint8_t serviceType) @@ -2043,5 +2043,4 @@ void Game::processCyclopediaCharacterDefenceStats(const CyclopediaCharacterDefen void Game::processCyclopediaCharacterMiscStats(const CyclopediaCharacterMiscStats& data) { g_lua.callGlobalField("g_game", "onCyclopediaCharacterMiscStats", data); -} - +} \ No newline at end of file diff --git a/src/client/game.h b/src/client/game.h index 58d9bd00a2..08d6d88866 100644 --- a/src/client/game.h +++ b/src/client/game.h @@ -778,7 +778,7 @@ class Game void sendPartyAnalyzerPriceType(); void sendPartyAnalyzerPriceValue(); // For action 3, will get items from cyclopedia void sendPartyAnalyzerAction(uint8_t action, const std::vector>& items = {}); - + // outfit related void requestOutfit(); void changeOutfit(const Outfit& outfit); @@ -887,7 +887,7 @@ class Game void setCustomOs(const Otc::OperatingSystem_t os) { m_clientCustomOs = os; } Otc::OperatingSystem_t getOs(); - bool canPerformGameAction() const; + [[nodiscard]] bool canPerformGameAction() const; bool isOnline() { return m_online; } bool isLogging() { return !m_online && m_protocolGame; } @@ -895,7 +895,7 @@ class Game bool isAttacking() { return !!m_attackingCreature && !m_attackingCreature->isRemoved(); } bool isFollowing() { return !!m_followingCreature && !m_followingCreature->isRemoved(); } bool isConnectionOk() { return m_protocolGame && m_protocolGame->getElapsedTicksSinceLastRead() < 5000; } - auto mapUpdatedAt() const { return m_mapUpdatedAt; } + [[nodiscard]] auto mapUpdatedAt() const { return m_mapUpdatedAt; } void resetMapUpdatedAt() { m_mapUpdatedAt = 0; } int getPing() { return m_ping; } diff --git a/src/client/gameconfig.h b/src/client/gameconfig.h index d5ff82ccd2..e62f92eda7 100644 --- a/src/client/gameconfig.h +++ b/src/client/gameconfig.h @@ -35,42 +35,42 @@ class GameConfig void terminate(); uint8_t getSpriteSize() { return m_spriteSize; } - uint16_t getLastSupportedVersion() const { return m_lastSupportedVersion; } - bool drawTyping() const { return m_drawTyping; } - std::string getTypingIcon() const { return m_typingIcon; } + [[nodiscard]] uint16_t getLastSupportedVersion() const { return m_lastSupportedVersion; } + [[nodiscard]] bool drawTyping() const { return m_drawTyping; } + [[nodiscard]] std::string getTypingIcon() const { return m_typingIcon; } - Size getMapViewPort() const { return m_mapViewPort; } - uint8_t getMapMaxZ() const { return m_mapMaxZ; } - uint8_t getMapSeaFloor() const { return m_mapSeaFloor; } - uint8_t getMapUndergroundFloorRange() const { return m_mapUndergroundFloorRange; } - uint8_t getMapAwareUndergroundFloorRange() const { return m_mapAwareUndergroundFloorRange; } + [[nodiscard]] Size getMapViewPort() const { return m_mapViewPort; } + [[nodiscard]] uint8_t getMapMaxZ() const { return m_mapMaxZ; } + [[nodiscard]] uint8_t getMapSeaFloor() const { return m_mapSeaFloor; } + [[nodiscard]] uint8_t getMapUndergroundFloorRange() const { return m_mapUndergroundFloorRange; } + [[nodiscard]] uint8_t getMapAwareUndergroundFloorRange() const { return m_mapAwareUndergroundFloorRange; } - uint8_t getTileMaxElevation() const { return m_tileMaxElevation; } - uint8_t getTileMaxThings() const { return m_tileMaxThings; } - uint8_t getTileTransparentFloorViewRange() const { return m_tileTransparentFloorViewRange; } + [[nodiscard]] uint8_t getTileMaxElevation() const { return m_tileMaxElevation; } + [[nodiscard]] uint8_t getTileMaxThings() const { return m_tileMaxThings; } + [[nodiscard]] uint8_t getTileTransparentFloorViewRange() const { return m_tileTransparentFloorViewRange; } bool isDrawingInformationByWidget() { return m_drawInformationByWidget; } - bool isForcingNewWalkingFormula() const { return m_forceNewWalkingFormula; } + [[nodiscard]] bool isForcingNewWalkingFormula() const { return m_forceNewWalkingFormula; } bool isAdjustCreatureInformationBasedCropSize() { return m_adjustCreatureInformationBasedCropSize; } bool isUseCropSizeForUIDraw() { return m_useCropSizeForUIDraw; } uint16_t getShieldBlinkTicks() { return m_shieldBlinkTicks; } - uint16_t getVolatileSquareDuration() const { return m_volatileSquareDuration; } - - uint16_t getInvisibleTicksPerFrame() const { return m_invisibleTicksPerFrame; } - uint16_t getItemTicksPerFrame() const { return m_itemTicksPerFrame; } - uint16_t getEffectTicksPerFrame() const { return m_effectTicksPerFrame; } - uint16_t getMissileTicksPerFrame() const { return m_missileTicksPerFrame; } - uint16_t getAnimatedTextDuration() const { return m_animatedTextDuration; } - uint16_t getStaticDurationPerCharacter() const { return m_staticDurationPerCharacter; } - uint16_t getMinStatictextDuration() const { return m_minStatictextDuration; } - - double getPlayerDiagonalWalkSpeed() const { return m_playerDiagonalWalkSpeed; } - double getCreatureDiagonalWalkSpeed() const { return m_creatureDiagonalWalkSpeed; } - - BitmapFontPtr getCreatureNameFont() const { return m_creatureNameFont; } - BitmapFontPtr getAnimatedTextFont() const { return m_animatedTextFont; } - BitmapFontPtr getStaticTextFont() const { return m_staticTextFont; } - BitmapFontPtr getWidgetTextFont() const { return m_widgetTextFont; } + [[nodiscard]] uint16_t getVolatileSquareDuration() const { return m_volatileSquareDuration; } + + [[nodiscard]] uint16_t getInvisibleTicksPerFrame() const { return m_invisibleTicksPerFrame; } + [[nodiscard]] uint16_t getItemTicksPerFrame() const { return m_itemTicksPerFrame; } + [[nodiscard]] uint16_t getEffectTicksPerFrame() const { return m_effectTicksPerFrame; } + [[nodiscard]] uint16_t getMissileTicksPerFrame() const { return m_missileTicksPerFrame; } + [[nodiscard]] uint16_t getAnimatedTextDuration() const { return m_animatedTextDuration; } + [[nodiscard]] uint16_t getStaticDurationPerCharacter() const { return m_staticDurationPerCharacter; } + [[nodiscard]] uint16_t getMinStatictextDuration() const { return m_minStatictextDuration; } + + [[nodiscard]] double getPlayerDiagonalWalkSpeed() const { return m_playerDiagonalWalkSpeed; } + [[nodiscard]] double getCreatureDiagonalWalkSpeed() const { return m_creatureDiagonalWalkSpeed; } + + [[nodiscard]] BitmapFontPtr getCreatureNameFont() const { return m_creatureNameFont; } + [[nodiscard]] BitmapFontPtr getAnimatedTextFont() const { return m_animatedTextFont; } + [[nodiscard]] BitmapFontPtr getStaticTextFont() const { return m_staticTextFont; } + [[nodiscard]] BitmapFontPtr getWidgetTextFont() const { return m_widgetTextFont; } std::string getCreatureNameFontName() { return m_creatureNameFont->getName(); } std::string getAnimatedTextFontName() { return m_animatedTextFont->getName(); } diff --git a/src/client/luafunctions.cpp b/src/client/luafunctions.cpp index ed5aa21906..ad1650b4d0 100644 --- a/src/client/luafunctions.cpp +++ b/src/client/luafunctions.cpp @@ -271,7 +271,7 @@ void Client::registerLuaFunctions() g_lua.bindSingletonFunction("g_game", "sendPartyAnalyzerReset", &Game::sendPartyAnalyzerReset, &g_game); g_lua.bindSingletonFunction("g_game", "sendPartyAnalyzerPriceType", &Game::sendPartyAnalyzerPriceType, &g_game); g_lua.bindSingletonFunction("g_game", "sendPartyAnalyzerPriceValue", &Game::sendPartyAnalyzerPriceValue, &g_game); - + g_lua.bindSingletonFunction("g_game", "requestOutfit", &Game::requestOutfit, &g_game); g_lua.bindSingletonFunction("g_game", "changeOutfit", &Game::changeOutfit, &g_game); g_lua.bindSingletonFunction("g_game", "addVip", &Game::addVip, &g_game); diff --git a/src/client/luavaluecasts_client.cpp b/src/client/luavaluecasts_client.cpp index e16ca5370a..0749f4b3c1 100644 --- a/src/client/luavaluecasts_client.cpp +++ b/src/client/luavaluecasts_client.cpp @@ -482,7 +482,6 @@ int push_luavalue(const SubOffer& subOffer) { g_lua.setField("basePrice"); } if (g_game.getClientVersion() < 1310) { - g_lua.pushString(subOffer.name); g_lua.setField("name"); g_lua.pushString(subOffer.description); @@ -532,7 +531,7 @@ int push_luavalue(const StoreOffer& offer) { g_lua.pushString(offer.reasonIdDisable); g_lua.setField("reasonIdDisable"); } - } else{ + } else { g_lua.pushBoolean(offer.configurable); g_lua.setField("configurable"); } @@ -833,11 +832,11 @@ int push_luavalue(const CharmData& charm) { g_lua.pushInteger(charm.removeRuneCost); g_lua.setField("removeRuneCost"); //if (g_game.getClientVersion() >= 1410) { - g_lua.pushInteger(charm.availableCharmSlots); - g_lua.setField("availableCharmSlots"); - g_lua.pushInteger(charm.tier); - g_lua.setField("tier"); - // } + g_lua.pushInteger(charm.availableCharmSlots); + g_lua.setField("availableCharmSlots"); + g_lua.pushInteger(charm.tier); + g_lua.setField("tier"); + // } return 1; } @@ -1636,4 +1635,4 @@ int push_luavalue(const PartyMemberName& data) { g_lua.pushString(data.memberName); g_lua.setField("memberName"); return 1; -} +} \ No newline at end of file diff --git a/src/client/map.cpp b/src/client/map.cpp index 4db0a7a040..b33c1c5966 100644 --- a/src/client/map.cpp +++ b/src/client/map.cpp @@ -110,7 +110,7 @@ void Map::clean() { cleanDynamicThings(); - for (auto i = -1; ++i <= g_gameConfig.getMapMaxZ();) + for (auto i = -1; std::cmp_less_equal(++i, g_gameConfig.getMapMaxZ());) m_floors[i].tileBlocks.clear(); #ifdef FRAMEWORK_EDITOR @@ -144,7 +144,7 @@ void Map::cleanDynamicThings() for (const auto& widget : widgets) widget->destroy(); - for (auto i = -1; ++i <= g_gameConfig.getMapMaxZ();) + for (auto i = -1; std::cmp_less_equal(++i, g_gameConfig.getMapMaxZ());) m_floors[i].missiles.clear(); for (auto& floor : m_floors) { @@ -374,12 +374,12 @@ const TilePtr& Map::getTile(const Position& pos) TileList Map::getTiles(const int8_t floor/* = -1*/) { TileList tiles; - if (floor > g_gameConfig.getMapMaxZ()) + if (std::cmp_greater(floor, g_gameConfig.getMapMaxZ())) return tiles; if (floor < 0) { // Search all floors - for (auto z = -1; ++z <= g_gameConfig.getMapMaxZ();) { + for (auto z = -1; std::cmp_less_equal(++z, g_gameConfig.getMapMaxZ());) { for (const auto& [key, block] : m_floors[z].tileBlocks) { for (const auto& tile : block.getTiles()) { if (tile != nullptr) @@ -553,7 +553,7 @@ void Map::removeUnawareThings() } : m_awareRange; // remove tiles that we are not aware anymore - for (auto z = -1; ++z <= g_gameConfig.getMapMaxZ();) { + for (auto z = -1; std::cmp_less_equal(++z, g_gameConfig.getMapMaxZ());) { auto& tileBlocks = m_floors[z].tileBlocks; for (auto it = tileBlocks.begin(); it != tileBlocks.end();) { auto& block = it->second; @@ -640,7 +640,7 @@ std::vector Map::getSpectatorsInRangeEx(const Position& centerPos, //TODO: optimize //TODO: delivery creatures in distance order - for (int iz = -minZRange; iz <= maxZRange; ++iz) { + for (int iz = -minZRange; std::cmp_less_equal(iz, maxZRange); ++iz) { for (int iy = -minYRange; iy <= maxYRange; ++iy) { for (int ix = -minXRange; ix <= maxXRange; ++ix) { if (const auto& tile = getTile(centerPos.translated(ix, iy, iz))) { @@ -744,7 +744,7 @@ bool Map::isAwareOfPosition(const Position& pos, const AwareRange& awareRange) c Position groundedPos = pos; while (groundedPos.z != m_centralPosition.z) { if (groundedPos.z > m_centralPosition.z) { - if (groundedPos.x == UINT16_MAX || groundedPos.y == UINT16_MAX) // When pos == 65535,65535,15 we cant go up to 65536,65536,14 + if (std::cmp_equal(groundedPos.x, UINT16_MAX) || std::cmp_equal(groundedPos.y, UINT16_MAX)) // When pos == 65535,65535,15 we cant go up to 65536,65536,14 break; groundedPos.coveredUp(); } else { @@ -851,7 +851,7 @@ std::tuple, Otc::PathFindResult> Map::findPath(const nodes[startPos] = currentNode; SNode* foundNode = nullptr; while (currentNode) { - if (static_cast(nodes.size()) > maxComplexity) { + if (std::cmp_greater(nodes.size(), maxComplexity)) { result = Otc::PathFindResultTooFar; break; } @@ -1321,7 +1321,7 @@ std::map> Map::findEveryPath std::unordered_map nodes; std::priority_queue, LessNode> searchList; - Node* initNode = new Node{ 1, 0, start, nullptr, 0, 0 }; + Node* initNode = new Node{ .cost = 1, .totalCost = 0, .pos = start, .prev = nullptr, .distance = 0, .unseen = 0 }; nodes[start] = initNode; searchList.push(initNode); @@ -1387,7 +1387,9 @@ std::map> Map::findEveryPath node->pos.toString()); } } else { - it = nodes.emplace(neighbor, new Node{ (float)speed, 10000000.0f, neighbor, node, node->distance + 1, wasSeen ? 0 : 1 }).first; + it = nodes.emplace(neighbor, new Node{ .cost = (float)speed, .totalCost = 10000000.0f, + .pos = neighbor, .prev = node, .distance = node->distance + 1, + .unseen = wasSeen ? 0 : 1 }).first; } } diff --git a/src/client/map.h b/src/client/map.h index 5ceeef396e..f41be8c140 100644 --- a/src/client/map.h +++ b/src/client/map.h @@ -120,7 +120,7 @@ class TileBlock uint32_t getTileIndex(const Position& pos) { return ((pos.y % BLOCK_SIZE) * BLOCK_SIZE) + (pos.x % BLOCK_SIZE); } - const std::array& getTiles() const { return m_tiles; } + [[nodiscard]] const std::array& getTiles() const { return m_tiles; } private: std::array m_tiles; @@ -217,7 +217,7 @@ class Map void addAnimatedText(const AnimatedTextPtr& txt, const Position& pos); bool removeAnimatedText(const AnimatedTextPtr& txt); - bool isWidgetAttached(const UIWidgetPtr& widget) const; + [[nodiscard]] bool isWidgetAttached(const UIWidgetPtr& widget) const; void addAttachedWidgetToObject(const UIWidgetPtr& widget, const AttachableObjectPtr& object); bool removeAttachedWidgetFromObject(const UIWidgetPtr& widget); void updateAttachedWidgets(const MapViewPtr& mapView); @@ -225,7 +225,7 @@ class Map void colorizeThing(const ThingPtr& thing, const Color& color); void removeThingColor(const ThingPtr& thing); - StaticTextPtr getStaticText(const Position& pos) const; + [[nodiscard]] StaticTextPtr getStaticText(const Position& pos) const; // tile related const TilePtr& createTile(const Position& pos); @@ -279,19 +279,19 @@ class Map bool isCovered(const Position& pos, bool& isLoading, uint8_t firstFloor = 0); bool isCompletelyCovered(const Position& pos, bool& isLoading, uint8_t firstFloor = 0); - bool isAwareOfPosition(const Position& pos) const { return isAwareOfPosition(pos, m_awareRange); } - bool isAwareOfPosition(const Position& pos, const AwareRange& awareRange) const; + [[nodiscard]] bool isAwareOfPosition(const Position& pos) const { return isAwareOfPosition(pos, m_awareRange); } + [[nodiscard]] bool isAwareOfPosition(const Position& pos, const AwareRange& awareRange) const; void resetLastCamera() const; void setAwareRange(const AwareRange& range); void resetAwareRange(); - AwareRange getAwareRange() const { return m_awareRange; } + [[nodiscard]] AwareRange getAwareRange() const { return m_awareRange; } - Light getLight() const { return m_light; } + [[nodiscard]] Light getLight() const { return m_light; } Position getCentralPosition() { return m_centralPosition; } - uint8_t getFirstAwareFloor() const; - uint8_t getLastAwareFloor() const; + [[nodiscard]] uint8_t getFirstAwareFloor() const; + [[nodiscard]] uint8_t getLastAwareFloor() const; const std::vector& getFloorMissiles(const uint8_t z) { return m_floors[z].missiles; } std::vector getAnimatedTexts() { return m_animatedTexts; } @@ -312,7 +312,7 @@ class Map int getMinimapColor(const Position& pos); bool isSightClear(const Position& fromPos, const Position& toPos); - const auto& getCreatures() const { return m_knownCreatures; } + [[nodiscard]] const auto& getCreatures() const { return m_knownCreatures; } private: struct FloorData diff --git a/src/client/mapview.cpp b/src/client/mapview.cpp index f972c8ecff..e6f902f324 100644 --- a/src/client/mapview.cpp +++ b/src/client/mapview.cpp @@ -127,14 +127,15 @@ void MapView::drawFloor() const uint32_t flags = Otc::DrawThings; - for (int_fast8_t z = m_floorMax; z >= m_floorMin; --z) { + for (int_fast8_t z = m_floorMax; std::cmp_greater_equal(z, m_floorMin); --z) { const float fadeLevel = getFadeLevel(z); if (fadeLevel == 0.f) break; if (fadeLevel < .99f) g_drawPool.setOpacity(fadeLevel); Position _camera = cameraPosition; - const bool alwaysTransparent = m_floorViewMode == ALWAYS_WITH_TRANSPARENCY && z < m_cachedFirstVisibleFloor && _camera.coveredUp(cameraPosition.z - z); + const bool alwaysTransparent = m_floorViewMode == ALWAYS_WITH_TRANSPARENCY && std::cmp_less(z, m_cachedFirstVisibleFloor) + && _camera.coveredUp(cameraPosition.z - z); const auto& map = m_floors[z].cachedVisibleTiles; @@ -186,12 +187,13 @@ void MapView::drawFloor() void MapView::drawLights() { const auto& cameraPosition = m_posInfo.camera; - for (int_fast8_t z = m_floorMax; z >= m_floorMin; --z) { + for (int_fast8_t z = m_floorMax; std::cmp_greater_equal(z, m_floorMin); --z) { const float fadeLevel = getFadeLevel(z); if (fadeLevel == 0.f) break; Position _camera = cameraPosition; - const bool alwaysTransparent = m_floorViewMode == ALWAYS_WITH_TRANSPARENCY && z < m_cachedFirstVisibleFloor && _camera.coveredUp(cameraPosition.z - z); + const bool alwaysTransparent = m_floorViewMode == ALWAYS_WITH_TRANSPARENCY && std::cmp_less(z, m_cachedFirstVisibleFloor) + && _camera.coveredUp(cameraPosition.z - z); const auto& map = m_floors[z].cachedVisibleTiles; @@ -320,19 +322,19 @@ void MapView::updateVisibleTiles() // Fading System by Kondra https://github.com/OTCv8/otclientv8 if (!m_lastCameraPosition.isValid() || m_lastCameraPosition.z != m_posInfo.camera.z || m_lastCameraPosition.distance(m_posInfo.camera) >= 3) { m_fadeType = FadeType::NONE; - for (int iz = m_cachedLastVisibleFloor; iz >= cachedFirstVisibleFloor; --iz) { + for (int iz = m_cachedLastVisibleFloor; std::cmp_greater_equal(iz, cachedFirstVisibleFloor); --iz) { m_floors[iz].fadingTimers.restart(m_floorFading); } } else if (prevFirstVisibleFloor < m_cachedFirstVisibleFloor) { // hiding new floor m_fadeType = FadeType::FADE_OUT; - for (int iz = prevFirstVisibleFloor; iz < m_cachedFirstVisibleFloor; ++iz) { + for (int iz = prevFirstVisibleFloor; std::cmp_less(iz, m_cachedFirstVisibleFloor); ++iz) { const int shift = std::max(0, m_floorFading - m_floors[iz].fadingTimers.ticksElapsed()); m_floors[iz].fadingTimers.restart(shift); } } else if (prevFirstVisibleFloor > m_cachedFirstVisibleFloor) { // showing floor m_fadeType = FadeType::FADE_IN; m_fadeFinish = false; - for (int iz = m_cachedFirstVisibleFloor; iz < prevFirstVisibleFloor; ++iz) { + for (int iz = m_cachedFirstVisibleFloor; std::cmp_less(iz, prevFirstVisibleFloor); ++iz) { const int shift = std::max(0, m_floorFading - m_floors[iz].fadingTimers.ticksElapsed()); m_floors[iz].fadingTimers.restart(shift); } @@ -348,11 +350,12 @@ void MapView::updateVisibleTiles() const uint32_t numDiagonals = m_drawDimension.width() + m_drawDimension.height() - 1; auto processDiagonalRange = [&](std::vector& floors, uint32_t start, uint32_t end) { - for (int_fast32_t iz = m_cachedLastVisibleFloor; iz >= cachedFirstVisibleFloor; --iz) { + for (int_fast32_t iz = m_cachedLastVisibleFloor; std::cmp_greater_equal(iz, cachedFirstVisibleFloor); --iz) { auto& floor = floors[iz].cachedVisibleTiles; for (uint_fast32_t diagonal = start; diagonal < end; ++diagonal) { - const auto advance = (static_cast(diagonal) >= static_cast(m_drawDimension.height())) ? diagonal - static_cast(m_drawDimension.height()) : 0; + const auto advance = (std::cmp_greater_equal(diagonal, m_drawDimension.height())) + ? diagonal - static_cast(m_drawDimension.height()) : 0; for (int iy = diagonal - advance, ix = advance; iy >= 0 && ix < m_drawDimension.width(); --iy, ++ix) { auto tilePos = m_posInfo.camera.translated(ix - m_virtualCenterOffset.x, iy - m_virtualCenterOffset.y); tilePos.coveredUp(m_posInfo.camera.z - iz); @@ -378,9 +381,9 @@ void MapView::updateVisibleTiles() } if (addTile || !floor.shades.empty()) { - if (iz < m_floorMin) + if (std::cmp_less(iz, m_floorMin)) m_floorMin = iz; - else if (iz > m_floorMax) + else if (std::cmp_greater(iz, m_floorMax)) m_floorMax = iz; } } diff --git a/src/client/mapview.h b/src/client/mapview.h index 8106ef486d..8e2044b8d3 100644 --- a/src/client/mapview.h +++ b/src/client/mapview.h @@ -34,10 +34,10 @@ struct AwareRange uint8_t right{ 0 }; uint8_t bottom{ 0 }; - uint8_t horizontal() const { return left + right + 1; } - uint8_t vertical() const { return top + bottom + 1; } + [[nodiscard]] uint8_t horizontal() const { return left + right + 1; } + [[nodiscard]] uint8_t vertical() const { return top + bottom + 1; } - Size dimension() const { return { left * 2 + 1 , top * 2 + 1 }; } + [[nodiscard]] Size dimension() const { return { left * 2 + 1 , top * 2 + 1 }; } bool operator==(const AwareRange& other) const { return left == other.left && top == other.top && right == other.right && bottom == other.bottom; } @@ -52,12 +52,12 @@ struct MapPosInfo float verticalStretchFactor; float scaleFactor; - bool isInRange(const Position& pos, const bool ignoreZ = false) const + [[nodiscard]] bool isInRange(const Position& pos, const bool ignoreZ = false) const { return camera.isInRange(pos, awareRange.left - 1, awareRange.right - 2, awareRange.top - 1, awareRange.bottom - 2, ignoreZ); } - bool isInRangeEx(const Position& pos, const bool ignoreZ = false) const + [[nodiscard]] bool isInRangeEx(const Position& pos, const bool ignoreZ = false) const { return camera.isInRange(pos, awareRange.left, awareRange.right, awareRange.top, awareRange.bottom, ignoreZ); } diff --git a/src/client/minimap.h b/src/client/minimap.h index cb9dbb6424..a1102fe324 100644 --- a/src/client/minimap.h +++ b/src/client/minimap.h @@ -45,8 +45,8 @@ struct MinimapTile uint8_t flags{ 0 }; uint8_t color{ 255 }; uint8_t speed{ 10 }; - bool hasFlag(const MinimapTileFlags flag) const { return flags & flag; } - int getSpeed() const { return speed * 10; } + [[nodiscard]] bool hasFlag(const MinimapTileFlags flag) const { return flags & flag; } + [[nodiscard]] int getSpeed() const { return speed * 10; } bool operator==(const MinimapTile& other) const { return color == other.color && flags == other.flags && speed == other.speed; } bool operator!=(const MinimapTile& other) const { return !(*this == other); } }; @@ -64,7 +64,7 @@ class MinimapBlock std::array& getTiles() { return m_tiles; } void mustUpdate() { m_mustUpdate = true; } void justSaw() { m_wasSeen = true; } - bool wasSeen() const { return m_wasSeen; } + [[nodiscard]] bool wasSeen() const { return m_wasSeen; } private: TexturePtr m_texture; ImagePtr m_image; diff --git a/src/client/outfit.h b/src/client/outfit.h index 43097c9731..678cc38ab3 100644 --- a/src/client/outfit.h +++ b/src/client/outfit.h @@ -56,34 +56,34 @@ class Outfit void resetClothes(); - uint16_t getId() const { return m_id; } - uint16_t getAuxId() const { return m_auxId; } - uint16_t getMount() const { return m_mount; } - uint16_t getFamiliar() const { return m_familiar; } - uint16_t getWing() const { return m_wing; } - uint16_t getAura() const { return m_aura; } - uint16_t getEffect() const { return m_effect; } - std::string getShader() const { return m_shader; } - - uint8_t getHead() const { return m_head; } - uint8_t getBody() const { return m_body; } - uint8_t getLegs() const { return m_legs; } - uint8_t getFeet() const { return m_feet; } - uint8_t getAddons() const { return m_addons; } - - bool hasMount() const { return m_mount > 0; } - - ThingCategory getCategory() const { return m_category; } - bool isCreature() const { return m_category == ThingCategoryCreature; } - bool isInvalid() const { return m_category == ThingInvalidCategory; } - bool isEffect() const { return m_category == ThingCategoryEffect; } - bool isItem() const { return m_category == ThingCategoryItem; } - bool isTemp() const { return m_temp; } - - Color getHeadColor() const { return m_headColor; } - Color getBodyColor() const { return m_bodyColor; } - Color getLegsColor() const { return m_legsColor; } - Color getFeetColor() const { return m_feetColor; } + [[nodiscard]] uint16_t getId() const { return m_id; } + [[nodiscard]] uint16_t getAuxId() const { return m_auxId; } + [[nodiscard]] uint16_t getMount() const { return m_mount; } + [[nodiscard]] uint16_t getFamiliar() const { return m_familiar; } + [[nodiscard]] uint16_t getWing() const { return m_wing; } + [[nodiscard]] uint16_t getAura() const { return m_aura; } + [[nodiscard]] uint16_t getEffect() const { return m_effect; } + [[nodiscard]] std::string getShader() const { return m_shader; } + + [[nodiscard]] uint8_t getHead() const { return m_head; } + [[nodiscard]] uint8_t getBody() const { return m_body; } + [[nodiscard]] uint8_t getLegs() const { return m_legs; } + [[nodiscard]] uint8_t getFeet() const { return m_feet; } + [[nodiscard]] uint8_t getAddons() const { return m_addons; } + + [[nodiscard]] bool hasMount() const { return m_mount > 0; } + + [[nodiscard]] ThingCategory getCategory() const { return m_category; } + [[nodiscard]] bool isCreature() const { return m_category == ThingCategoryCreature; } + [[nodiscard]] bool isInvalid() const { return m_category == ThingInvalidCategory; } + [[nodiscard]] bool isEffect() const { return m_category == ThingCategoryEffect; } + [[nodiscard]] bool isItem() const { return m_category == ThingCategoryItem; } + [[nodiscard]] bool isTemp() const { return m_temp; } + + [[nodiscard]] Color getHeadColor() const { return m_headColor; } + [[nodiscard]] Color getBodyColor() const { return m_bodyColor; } + [[nodiscard]] Color getLegsColor() const { return m_legsColor; } + [[nodiscard]] Color getFeetColor() const { return m_feetColor; } bool operator==(const Outfit& other) const { diff --git a/src/client/position.cpp b/src/client/position.cpp index 3b4ca8b3b3..2cf665db7b 100644 --- a/src/client/position.cpp +++ b/src/client/position.cpp @@ -21,14 +21,18 @@ */ #include "position.h" + #include "gameconfig.h" -bool Position::isMapPosition() const { return ((x >= 0) && (y >= 0) && (x < UINT16_MAX) && (y < UINT16_MAX) && (z <= g_gameConfig.getMapMaxZ())); } +bool Position::isMapPosition() const { + return ((x >= 0) && (y >= 0) && (std::cmp_less(x, UINT16_MAX)) && ( + std::cmp_less(y, UINT16_MAX)) && (z <= g_gameConfig.getMapMaxZ())); +} bool Position::up(const int8_t n) { const int8_t nz = z - n; - if (nz >= 0 && nz <= g_gameConfig.getMapMaxZ()) { + if (nz >= 0 && std::cmp_less_equal(nz, g_gameConfig.getMapMaxZ())) { z = nz; return true; } @@ -38,7 +42,7 @@ bool Position::up(const int8_t n) bool Position::down(const int8_t n) { const int8_t nz = z + n; - if (nz >= 0 && nz <= g_gameConfig.getMapMaxZ()) { + if (nz >= 0 && std::cmp_less_equal(nz, g_gameConfig.getMapMaxZ())) { z = nz; return true; } @@ -50,7 +54,8 @@ bool Position::coveredUp(const int8_t n) { const int32_t nx = x + n, ny = y + n; const int8_t nz = z - n; - if (nx >= 0 && nx <= UINT16_MAX && ny >= 0 && ny <= UINT16_MAX && nz >= 0 && nz <= g_gameConfig.getMapMaxZ()) { + if (nx >= 0 && std::cmp_less_equal(nx, UINT16_MAX) && ny >= 0 && std::cmp_less_equal(ny, UINT16_MAX) && nz >= 0 && + std::cmp_less_equal(nz, g_gameConfig.getMapMaxZ())) { x = nx; y = ny; z = nz; return true; } @@ -62,7 +67,8 @@ bool Position::coveredDown(const int8_t n) { const int32_t nx = x - n, ny = y - n; const int8_t nz = z + n; - if (nx >= 0 && nx <= UINT16_MAX && ny >= 0 && ny <= UINT16_MAX && nz >= 0 && nz <= g_gameConfig.getMapMaxZ()) { + if (nx >= 0 && std::cmp_less_equal(nx, UINT16_MAX) && ny >= 0 && std::cmp_less_equal(ny, UINT16_MAX) && nz >= 0 && + std::cmp_less_equal(nz, g_gameConfig.getMapMaxZ())) { x = nx; y = ny; z = nz; return true; } diff --git a/src/client/position.h b/src/client/position.h index f87e5f86d7..954bdc9ca0 100644 --- a/src/client/position.h +++ b/src/client/position.h @@ -31,6 +31,7 @@ #include #include #include + #include #include @@ -42,7 +43,7 @@ class Position Position(const int32_t x, const int32_t y, const uint8_t z) : x(x), y(y), z(z) {} Position(const Position& position) = default; - Position translatedToDirection(const Otc::Direction direction) const + [[nodiscard]] Position translatedToDirection(const Otc::Direction direction) const { Position pos = *this; switch (direction) { @@ -80,7 +81,7 @@ class Position return pos; } - Position translatedToReverseDirection(const Otc::Direction direction) const + [[nodiscard]] Position translatedToReverseDirection(const Otc::Direction direction) const { Position pos = *this; switch (direction) { @@ -118,7 +119,7 @@ class Position return pos; } - std::vector translatedToDirections(const std::vector& dirs) const + [[nodiscard]] std::vector translatedToDirections(const std::vector& dirs) const { Position lastPos = *this; std::vector positions; @@ -155,7 +156,7 @@ class Position return angle; } - double getAngleFromPosition(const Position& position) const { return getAngleFromPositions(*this, position); } + [[nodiscard]] double getAngleFromPosition(const Position& position) const { return getAngleFromPositions(*this, position); } static Otc::Direction getDirectionFromPositions(const Position& fromPos, const Position& toPos) { @@ -188,17 +189,17 @@ class Position return Otc::InvalidDirection; } - Otc::Direction getDirectionFromPosition(const Position& position) const { return getDirectionFromPositions(*this, position); } + [[nodiscard]] Otc::Direction getDirectionFromPosition(const Position& position) const { return getDirectionFromPositions(*this, position); } - bool isMapPosition() const; - bool isValid() const { return !(x == UINT16_MAX && y == UINT16_MAX && z == UINT8_MAX); } - double distance(const Position& pos) const { return sqrt(pow(pos.x - x, 2) + pow(pos.y - y, 2)); } - uint16_t manhattanDistance(const Position& pos) const { return static_cast(std::abs(pos.x - x) + std::abs(pos.y - y)); } + [[nodiscard]] bool isMapPosition() const; + [[nodiscard]] bool isValid() const { return !(std::cmp_equal(x, UINT16_MAX) && std::cmp_equal(y, UINT16_MAX) && z == UINT8_MAX); } + [[nodiscard]] double distance(const Position& pos) const { return sqrt(pow(pos.x - x, 2) + pow(pos.y - y, 2)); } + [[nodiscard]] uint16_t manhattanDistance(const Position& pos) const { return static_cast(std::abs(pos.x - x) + std::abs(pos.y - y)); } void translate(const int32_t dx, const int32_t dy, const int8_t dz = 0) { x += dx; y += dy; z += dz; } - Position translated(const int32_t dx, const int32_t dy, const int8_t dz = 0) const { Position pos = *this; pos.x += dx; pos.y += dy; pos.z += dz; return pos; } + [[nodiscard]] Position translated(const int32_t dx, const int32_t dy, const int8_t dz = 0) const { Position pos = *this; pos.x += dx; pos.y += dy; pos.z += dz; return pos; } - std::array getPositionsAround() const + [[nodiscard]] std::array getPositionsAround() const { std::array positions; int_fast8_t i = -1; @@ -227,7 +228,7 @@ class Position bool operator==(const Position& other) const { return other.x == x && other.y == y && other.z == z; } bool operator!=(const Position& other) const { return other.x != x || other.y != y || other.z != z; } - bool isInRange(const Position& pos, const uint16_t xRange, const uint16_t yRange, const bool ignoreZ = false) const + [[nodiscard]] bool isInRange(const Position& pos, const uint16_t xRange, const uint16_t yRange, const bool ignoreZ = false) const { auto _pos = pos; if (pos.z != z) { @@ -238,7 +239,7 @@ class Position return std::abs(x - _pos.x) <= xRange && std::abs(y - _pos.y) <= yRange && z == pos.z; } - bool isInRange(const Position& pos, const uint16_t minXRange, const uint16_t maxXRange, const uint16_t minYRange, const uint16_t maxYRange, const bool ignoreZ = false) const + [[nodiscard]] bool isInRange(const Position& pos, const uint16_t minXRange, const uint16_t maxXRange, const uint16_t minYRange, const uint16_t maxYRange, const bool ignoreZ = false) const { auto _pos = pos; if (pos.z != z) { @@ -257,7 +258,7 @@ class Position bool coveredUp(int8_t n = 1); bool coveredDown(int8_t n = 1); - std::string toString() const + [[nodiscard]] std::string toString() const { return std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z); } @@ -296,7 +297,8 @@ inline std::istream& operator>>(std::istream& in, Position& pos) // Auto format Position template <> -struct fmt::formatter : fmt::formatter { +struct fmt::formatter : fmt::formatter +{ auto format(const Position& pos, fmt::format_context& ctx) const { return fmt::formatter::format(pos.toString(), ctx); } diff --git a/src/client/protocolgame.h b/src/client/protocolgame.h index 0f0e4d8fdf..988ce0dc78 100644 --- a/src/client/protocolgame.h +++ b/src/client/protocolgame.h @@ -28,32 +28,35 @@ #include #include -struct BossCooldownData { +struct BossCooldownData +{ uint32_t bossRaceId; uint64_t cooldownTime; - + BossCooldownData(uint32_t raceId, uint64_t cooldown) : bossRaceId(raceId), cooldownTime(cooldown) {} }; -struct PartyMemberData { +struct PartyMemberData +{ uint32_t memberID; uint8_t highlight; uint64_t loot; uint64_t supply; uint64_t damage; uint64_t healing; - + PartyMemberData(uint32_t id, uint8_t highlightValue, uint64_t lootValue, uint64_t supplyValue, uint64_t damageValue, uint64_t healingValue) : memberID(id), highlight(highlightValue), loot(lootValue), supply(supplyValue), damage(damageValue), healing(healingValue) {} }; -struct PartyMemberName { +struct PartyMemberName +{ uint32_t memberID; std::string memberName; - - PartyMemberName(uint32_t id, const std::string& name) - : memberID(id), memberName(name) {} + + PartyMemberName(uint32_t id, std::string name) + : memberID(id), memberName(std::move(name)) {} }; class ProtocolGame final : public Protocol @@ -414,7 +417,7 @@ class ProtocolGame final : public Protocol bool m_gameInitialized{ false }; bool m_mapKnown{ false }; bool m_firstRecv{ true }; - bool m_record {false}; + bool m_record{ false }; ticks_t m_lastPartyAnalyzerCall{ 0 }; diff --git a/src/client/protocolgameparse.cpp b/src/client/protocolgameparse.cpp index b31b340756..41590d0944 100644 --- a/src/client/protocolgameparse.cpp +++ b/src/client/protocolgameparse.cpp @@ -35,6 +35,7 @@ #include "thingtypemanager.h" #include "tile.h" #include + #include void ProtocolGame::parseMessage(const InputMessagePtr& msg) @@ -782,7 +783,7 @@ void ProtocolGame::parseStore(const InputMessagePtr& msg) const const uint16_t categoryCount = msg->getU16(); std::vector categories; - for (auto i = 0; i < categoryCount; ++i) { + for (auto i = 0; std::cmp_less(i, categoryCount); ++i) { StoreCategory category; category.name = msg->getString(); @@ -797,7 +798,7 @@ void ProtocolGame::parseStore(const InputMessagePtr& msg) const } const uint8_t iconCount = msg->getU8(); - for (auto j = 0; j < iconCount; ++j) { + for (auto j = 0; std::cmp_less(j, iconCount); ++j) { category.icons.push_back(msg->getString()); } @@ -915,7 +916,7 @@ void ProtocolGame::parseStoreTransactionHistory(const InputMessagePtr& msg) cons const uint8_t entries = msg->getU8(); std::vector> historyData; - for (auto i = 0; i < entries; ++i) { + for (auto i = 0; std::cmp_less(i, entries); ++i) { if (g_game.getClientVersion() >= 1291) { msg->getU32(); // transactionId const uint32_t time = msg->getU32(); @@ -945,226 +946,226 @@ void ProtocolGame::parseStoreTransactionHistory(const InputMessagePtr& msg) cons void ProtocolGame::parseStoreOffers(const InputMessagePtr& msg) { - if (g_game.getClientVersion() >= 1291) { - StoreData storeData; - storeData.categoryName = msg->getString(); - storeData.redirectId = msg->getU32(); + if (g_game.getClientVersion() >= 1291) { + StoreData storeData; + storeData.categoryName = msg->getString(); + storeData.redirectId = msg->getU32(); - msg->getU8(); // -- sort by 0 - most popular, 1 - alphabetically, 2 - newest - const uint8_t dropMenuShowAll = msg->getU8(); - for (auto i = 0; i < dropMenuShowAll; ++i) { + msg->getU8(); // -- sort by 0 - most popular, 1 - alphabetically, 2 - newest + const uint8_t dropMenuShowAll = msg->getU8(); + for (auto i = 0; std::cmp_less(i, dropMenuShowAll); ++i) { const auto& menu = msg->getString(); storeData.menuFilter.push_back(menu); - } - - uint16_t stringLength = msg->getU16(); + } + + uint16_t stringLength = msg->getU16(); msg->skipBytes(stringLength); // tfs send string , canary send u16 if (g_game.getClientVersion() >= 1310) { const uint16_t disableReasonsSize = msg->getU16(); - for (auto i = 0; i < disableReasonsSize; ++i) { + for (auto i = 0; std::cmp_less(i, disableReasonsSize); ++i) { const auto& reason = msg->getString(); storeData.disableReasons.push_back(reason); } } - const uint16_t offersCount = msg->getU16(); - if (storeData.categoryName == "Home") { - for (auto i = 0; i < offersCount; ++i) { - HomeOffer offer; - offer.name = msg->getString(); - offer.unknownByte = msg->getU8(); - offer.id = msg->getU32(); - offer.unknownU16 = msg->getU16(); - offer.price = msg->getU32(); - offer.coinType = msg->getU8(); - - const uint8_t hasDisabledReason = msg->getU8(); - if (hasDisabledReason == 1) { - msg->skipBytes(1); + const uint16_t offersCount = msg->getU16(); + if (storeData.categoryName == "Home") { + for (auto i = 0; std::cmp_less(i, offersCount); ++i) { + HomeOffer offer; + offer.name = msg->getString(); + offer.unknownByte = msg->getU8(); + offer.id = msg->getU32(); + offer.unknownU16 = msg->getU16(); + offer.price = msg->getU32(); + offer.coinType = msg->getU8(); + + const uint8_t hasDisabledReason = msg->getU8(); + if (hasDisabledReason == 1) { + msg->skipBytes(1); if (g_game.getClientVersion() >= 1300) { offer.disabledReasonIndex = msg->getU16(); - } else{ + } else { msg->getString(); } - } - - offer.unknownByte2 = msg->getU8(); - offer.type = msg->getU8(); - - if (offer.type == Otc::GameStoreInfoType_t::SHOW_NONE) { - offer.icon = msg->getString(); - } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_MOUNT) { - offer.mountClientId = msg->getU16(); - } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_ITEM) { - offer.itemType = msg->getU16(); - } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_OUTFIT) { - offer.sexId = msg->getU16(); - offer.outfit.lookHead = msg->getU8(); - offer.outfit.lookBody = msg->getU8(); - offer.outfit.lookLegs = msg->getU8(); - offer.outfit.lookFeet = msg->getU8(); - } - - offer.tryOnType = msg->getU8(); - offer.collection = msg->getU16(); - offer.popularityScore = msg->getU16(); - offer.stateNewUntil = msg->getU32(); - offer.userConfiguration = msg->getU8(); - offer.productsCapacity = msg->getU16(); - - storeData.homeOffers.push_back(offer); - } - - const uint8_t bannerCount = msg->getU8(); - - for (auto i = 0; i < bannerCount; ++i) { - Banner banner; - banner.image = msg->getString(); - banner.bannerType = msg->getU8(); - banner.offerId = msg->getU32(); - banner.unknownByte1 = msg->getU8(); - banner.unknownByte2 = msg->getU8(); - storeData.banners.push_back(banner); - } - - storeData.bannerDelay = msg->getU8(); - - g_lua.callGlobalField("g_game", "onParseStoreCreateHome", storeData); - return; - } - - for (auto i = 0; i < offersCount; ++i) { - StoreOffer offer; - offer.name = msg->getString(); - - const uint8_t subOffersCount = msg->getU8(); - for (auto j = 0; j < subOffersCount; ++j) { - SubOffer subOffer{}; - subOffer.id = msg->getU32(); - subOffer.count = msg->getU16(); - subOffer.price = msg->getU32(); - subOffer.coinType = msg->getU8(); - subOffer.disabled = msg->getU8() == 1; - if (subOffer.disabled) { - const uint8_t reason = msg->getU8(); - for (auto k = 0; k < reason; ++k) { + } + + offer.unknownByte2 = msg->getU8(); + offer.type = msg->getU8(); + + if (offer.type == Otc::GameStoreInfoType_t::SHOW_NONE) { + offer.icon = msg->getString(); + } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_MOUNT) { + offer.mountClientId = msg->getU16(); + } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_ITEM) { + offer.itemType = msg->getU16(); + } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_OUTFIT) { + offer.sexId = msg->getU16(); + offer.outfit.lookHead = msg->getU8(); + offer.outfit.lookBody = msg->getU8(); + offer.outfit.lookLegs = msg->getU8(); + offer.outfit.lookFeet = msg->getU8(); + } + + offer.tryOnType = msg->getU8(); + offer.collection = msg->getU16(); + offer.popularityScore = msg->getU16(); + offer.stateNewUntil = msg->getU32(); + offer.userConfiguration = msg->getU8(); + offer.productsCapacity = msg->getU16(); + + storeData.homeOffers.push_back(offer); + } + + const uint8_t bannerCount = msg->getU8(); + + for (auto i = 0; std::cmp_less(i, bannerCount); ++i) { + Banner banner; + banner.image = msg->getString(); + banner.bannerType = msg->getU8(); + banner.offerId = msg->getU32(); + banner.unknownByte1 = msg->getU8(); + banner.unknownByte2 = msg->getU8(); + storeData.banners.push_back(banner); + } + + storeData.bannerDelay = msg->getU8(); + + g_lua.callGlobalField("g_game", "onParseStoreCreateHome", storeData); + return; + } + + for (auto i = 0; std::cmp_less(i, offersCount); ++i) { + StoreOffer offer; + offer.name = msg->getString(); + + const uint8_t subOffersCount = msg->getU8(); + for (auto j = 0; std::cmp_less(j, subOffersCount); ++j) { + SubOffer subOffer{}; + subOffer.id = msg->getU32(); + subOffer.count = msg->getU16(); + subOffer.price = msg->getU32(); + subOffer.coinType = msg->getU8(); + subOffer.disabled = msg->getU8() == 1; + if (subOffer.disabled) { + const uint8_t reason = msg->getU8(); + for (auto k = 0; std::cmp_less(k, reason); ++k) { if (g_game.getClientVersion() >= 1300) { subOffer.reasonIdDisable = msg->getU16(); } else { msg->getString(); } - } - } - subOffer.state = msg->getU8(); - - if (subOffer.state == Otc::GameStoreInfoStatesType_t::STATE_SALE) { - subOffer.validUntil = msg->getU32(); - subOffer.basePrice = msg->getU32(); - } - offer.subOffers.push_back(subOffer); - } - - offer.type = msg->getU8(); - if (offer.type == Otc::GameStoreInfoType_t::SHOW_NONE) { - offer.icon = msg->getString(); - } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_MOUNT) { - offer.mountId = msg->getU16(); - } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_ITEM) { - offer.itemId = msg->getU16(); - } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_OUTFIT) { - offer.outfitId = msg->getU16(); - offer.outfitHead = msg->getU8(); - offer.outfitBody = msg->getU8(); - offer.outfitLegs = msg->getU8(); - offer.outfitFeet = msg->getU8(); - } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_HIRELING) { - offer.sex = msg->getU8(); - offer.maleOutfitId = msg->getU16(); - offer.femaleOutfitId = msg->getU16(); - offer.outfitHead = msg->getU8(); - offer.outfitBody = msg->getU8(); - offer.outfitLegs = msg->getU8(); - offer.outfitFeet = msg->getU8(); - } - - offer.tryOnType = msg->getU8(); - - if (g_game.getClientVersion() <= 1310) { - auto test = msg->getString(); - } else { - offer.collection = msg->getU16(); - } - - offer.popularityScore = msg->getU16(); - offer.stateNewUntil = msg->getU32(); - offer.configurable = msg->getU8() == 1; - offer.productsCapacity = msg->getU16(); - for (auto j = 0; j < offer.productsCapacity; ++j) { + } + } + subOffer.state = msg->getU8(); + + if (subOffer.state == Otc::GameStoreInfoStatesType_t::STATE_SALE) { + subOffer.validUntil = msg->getU32(); + subOffer.basePrice = msg->getU32(); + } + offer.subOffers.push_back(subOffer); + } + + offer.type = msg->getU8(); + if (offer.type == Otc::GameStoreInfoType_t::SHOW_NONE) { + offer.icon = msg->getString(); + } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_MOUNT) { + offer.mountId = msg->getU16(); + } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_ITEM) { + offer.itemId = msg->getU16(); + } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_OUTFIT) { + offer.outfitId = msg->getU16(); + offer.outfitHead = msg->getU8(); + offer.outfitBody = msg->getU8(); + offer.outfitLegs = msg->getU8(); + offer.outfitFeet = msg->getU8(); + } else if (offer.type == Otc::GameStoreInfoType_t::SHOW_HIRELING) { + offer.sex = msg->getU8(); + offer.maleOutfitId = msg->getU16(); + offer.femaleOutfitId = msg->getU16(); + offer.outfitHead = msg->getU8(); + offer.outfitBody = msg->getU8(); + offer.outfitLegs = msg->getU8(); + offer.outfitFeet = msg->getU8(); + } + + offer.tryOnType = msg->getU8(); + + if (g_game.getClientVersion() <= 1310) { + auto test = msg->getString(); + } else { + offer.collection = msg->getU16(); + } + + offer.popularityScore = msg->getU16(); + offer.stateNewUntil = msg->getU32(); + offer.configurable = msg->getU8() == 1; + offer.productsCapacity = msg->getU16(); + for (auto j = 0; std::cmp_less(j, offer.productsCapacity); ++j) { msg->getString(); msg->getU8(); // info in description? msg->getU16(); } - storeData.storeOffers.push_back(offer); - } - - if (storeData.categoryName == "Search") { - storeData.tooManyResults = msg->getU8() == 1; - } - - g_lua.callGlobalField("g_game", "onParseStoreCreateProducts", storeData); - } else { - StoreData storeData; - storeData.categoryName = msg->getString(); // categoryName - - const uint16_t offersCount = msg->getU16(); - for (auto i = 0; i < offersCount; ++i) { - StoreOffer offer; - offer.id = msg->getU32(); // offerId - offer.name = msg->getString(); // offerName - offer.description = msg->getString(); // offerDescription - offer.price = msg->getU32(); // price - - const uint8_t highlightState = msg->getU8(); - if (highlightState == 2 && g_game.getFeature(Otc::GameIngameStoreHighlights) && g_game.getClientVersion() >= 1097) { - offer.state = Otc::GameStoreInfoStatesType_t::STATE_SALE; - offer.stateNewUntil = msg->getU32(); // saleValidUntilTimestamp - offer.basePrice = msg->getU32(); // basePrice - } else { - offer.state = highlightState; - } + storeData.storeOffers.push_back(offer); + } + + if (storeData.categoryName == "Search") { + storeData.tooManyResults = msg->getU8() == 1; + } + + g_lua.callGlobalField("g_game", "onParseStoreCreateProducts", storeData); + } else { + StoreData storeData; + storeData.categoryName = msg->getString(); // categoryName + + const uint16_t offersCount = msg->getU16(); + for (auto i = 0; std::cmp_less(i, offersCount); ++i) { + StoreOffer offer; + offer.id = msg->getU32(); // offerId + offer.name = msg->getString(); // offerName + offer.description = msg->getString(); // offerDescription + offer.price = msg->getU32(); // price + + const uint8_t highlightState = msg->getU8(); + if (highlightState == 2 && g_game.getFeature(Otc::GameIngameStoreHighlights) && g_game.getClientVersion() >= 1097) { + offer.state = Otc::GameStoreInfoStatesType_t::STATE_SALE; + offer.stateNewUntil = msg->getU32(); // saleValidUntilTimestamp + offer.basePrice = msg->getU32(); // basePrice + } else { + offer.state = highlightState; + } offer.disabled = msg->getU8() == 1; if (g_game.getFeature(Otc::GameIngameStoreHighlights) && offer.disabled) { offer.reasonIdDisable = msg->getString(); // disabledReason } - const uint8_t iconCount = msg->getU8(); - for (auto j = 0; j < iconCount; ++j) { - offer.icon = msg->getString(); // icon - } + const uint8_t iconCount = msg->getU8(); + for (auto j = 0; std::cmp_less(j, iconCount); ++j) { + offer.icon = msg->getString(); // icon + } - const uint16_t subOffersCount = msg->getU16(); + const uint16_t subOffersCount = msg->getU16(); - for (auto j = 0; j < subOffersCount; ++j) { - SubOffer subOffer; - subOffer.name = msg->getString(); // name - subOffer.description = msg->getString(); // description + for (auto j = 0; std::cmp_less(j, subOffersCount); ++j) { + SubOffer subOffer; + subOffer.name = msg->getString(); // name + subOffer.description = msg->getString(); // description - const uint8_t subIconsCount = msg->getU8(); - for (auto k = 0; k < subIconsCount; ++k) { - subOffer.icons.push_back(msg->getString()); // icon - } - subOffer.parent = msg->getString(); // serviceType - offer.subOffers.push_back(subOffer); - } + const uint8_t subIconsCount = msg->getU8(); + for (auto k = 0; std::cmp_less(k, subIconsCount); ++k) { + subOffer.icons.push_back(msg->getString()); // icon + } + subOffer.parent = msg->getString(); // serviceType + offer.subOffers.push_back(subOffer); + } - storeData.storeOffers.push_back(offer); - } + storeData.storeOffers.push_back(offer); + } - g_lua.callGlobalField("g_game", "onParseStoreCreateProducts", storeData); - } + g_lua.callGlobalField("g_game", "onParseStoreCreateProducts", storeData); + } } void ProtocolGame::parseStoreError(const InputMessagePtr& msg) const @@ -1178,7 +1179,7 @@ void ProtocolGame::parseStoreError(const InputMessagePtr& msg) const void ProtocolGame::parseUnjustifiedStats(const InputMessagePtr& msg) { const uint8_t killsDay = msg->getU8(); //dayProgress % - const uint8_t killsDayRemaining = msg->getU8(); + const uint8_t killsDayRemaining = msg->getU8(); const uint8_t killsWeek = msg->getU8(); //weekProgress % const uint8_t killsWeekRemaining = msg->getU8(); const uint8_t killsMonth = msg->getU8(); //monthProgress % @@ -1224,7 +1225,7 @@ void ProtocolGame::parseGMActions(const InputMessagePtr& msg) std::vector actions; - for (auto i = 0; i < numViolationReasons; ++i) { + for (auto i = 0; std::cmp_less(i, numViolationReasons); ++i) { actions.push_back(msg->getU8()); } @@ -1486,14 +1487,14 @@ void ProtocolGame::parseOpenContainer(const InputMessagePtr& msg) std::vector items; items.reserve(itemCount); - for (auto i = 0; i < itemCount; i++) { + for (auto i = 0; std::cmp_less(i, itemCount); i++) { items.push_back(getItem(msg)); } if (g_game.getFeature(Otc::GameContainerFilter)) { msg->getU8(); // category const uint8_t categoriesSize = msg->getU8(); - for (auto i = 0; i < categoriesSize; ++i) { + for (auto i = 0; std::cmp_less(i, categoriesSize); ++i) { msg->getU8(); // id msg->getString(); // name } @@ -1556,7 +1557,7 @@ void ProtocolGame::parseBosstiaryInfo(const InputMessagePtr& msg) const uint16_t bosstiaryRaceLast = msg->getU16(); std::vector bossData; - for (auto i = 0; i < bosstiaryRaceLast; ++i) { + for (auto i = 0; std::cmp_less(i, bosstiaryRaceLast); ++i) { BosstiaryData boss; boss.raceId = msg->getU32(); boss.category = msg->getU8(); @@ -1587,7 +1588,7 @@ void ProtocolGame::parseCyclopediaItemDetail(const InputMessagePtr& msg) std::vector> descriptions; descriptions.reserve(descriptionsSize); - for (auto i = 0; i < descriptionsSize; ++i) { + for (auto i = 0; std::cmp_less(i, descriptionsSize); ++i) { const auto& firstDescription = msg->getString(); const auto& secondDescription = msg->getString(); descriptions.emplace_back(firstDescription, secondDescription); @@ -1624,7 +1625,7 @@ void ProtocolGame::parseOpenNpcTrade(const InputMessagePtr& msg) const uint16_t listCount = g_game.getClientVersion() >= 900 ? msg->getU16() : msg->getU8(); std::vector> items; - for (auto i = 0; i < listCount; ++i) { + for (auto i = 0; std::cmp_less(i, listCount); ++i) { const uint16_t itemId = msg->getU16(); const uint8_t itemCount = msg->getU8(); @@ -1655,7 +1656,7 @@ void ProtocolGame::parsePlayerGoods(const InputMessagePtr& msg) const const uint8_t itemsListSize = g_game.getClientVersion() >= 1334 ? msg->getU16() : msg->getU8(); std::vector> goods; - for (auto i = 0; i < itemsListSize; ++i) { + for (auto i = 0; std::cmp_less(i, itemsListSize); ++i) { const uint16_t itemId = msg->getU16(); const uint16_t itemAmount = g_game.getFeature(Otc::GameDoubleShopSellAmount) ? msg->getU16() : msg->getU8(); @@ -1675,7 +1676,7 @@ void ProtocolGame::parseOwnTrade(const InputMessagePtr& msg) std::vector items; items.reserve(count); - for (auto i = 0; i < count; i++) { + for (auto i = 0; std::cmp_less(i, count); i++) { items.push_back(getItem(msg)); } @@ -1690,7 +1691,7 @@ void ProtocolGame::parseCounterTrade(const InputMessagePtr& msg) std::vector items; items.reserve(count); - for (auto i = 0; i < count; i++) { + for (auto i = 0; std::cmp_less(i, count); i++) { items.push_back(getItem(msg)); } @@ -1850,12 +1851,12 @@ void ProtocolGame::parseDistanceMissile(const InputMessagePtr& msg) void ProtocolGame::parseItemClasses(const InputMessagePtr& msg) { const uint8_t classSize = msg->getU8(); - for (auto i = 0; i < classSize; ++i) { + for (auto i = 0; std::cmp_less(i, classSize); ++i) { msg->getU8(); // class id // tiers const uint8_t tiersSize = msg->getU8(); - for (auto j = 0; j < tiersSize; ++j) { + for (auto j = 0; std::cmp_less(j, tiersSize); ++j) { msg->getU8(); // tier id msg->getU64(); // upgrade cost } @@ -1863,7 +1864,7 @@ void ProtocolGame::parseItemClasses(const InputMessagePtr& msg) if (g_game.getFeature(Otc::GameDynamicForgeVariables)) { const uint8_t grades = msg->getU8(); - for (auto i = 0; i < grades; ++i) { + for (auto i = 0; std::cmp_less(i, grades); ++i) { msg->getU8(); // Tier msg->getU8(); // Exalted cores } @@ -1871,14 +1872,14 @@ void ProtocolGame::parseItemClasses(const InputMessagePtr& msg) if (g_game.getFeature(Otc::GameForgeConvergence)) { // Convergence fusion prices per tier const uint8_t totalConvergenceFusion = msg->getU8(); // total size count - for (auto i = 0; i < totalConvergenceFusion; ++i) { + for (auto i = 0; std::cmp_less(i, totalConvergenceFusion); ++i) { msg->getU8(); // tier id msg->getU64(); // upgrade cost } // Convergence transfer prices per tier const uint8_t totalConvergenceTransfer = msg->getU8(); // total size count - for (auto i = 0; i < totalConvergenceTransfer; ++i) { + for (auto i = 0; std::cmp_less(i, totalConvergenceTransfer); ++i) { msg->getU8(); // tier id msg->getU64(); // upgrade cost } @@ -1916,7 +1917,7 @@ void ProtocolGame::parseItemClasses(const InputMessagePtr& msg) totalForgeValues = totalForgeValues + 2; } - for (auto i = 0; i < totalForgeValues; ++i) { + for (auto i = 0; std::cmp_less(i, totalForgeValues); ++i) { msg->getU8(); // Forge values } } @@ -1944,7 +1945,7 @@ void ProtocolGame::parseTrappers(const InputMessagePtr& msg) g_logger.traceError("ProtocolGame::parseTrappers: too many trappers"); } - for (auto i = 0; i < numTrappers; ++i) { + for (auto i = 0; std::cmp_less(i, numTrappers); ++i) { const uint32_t creatureId = msg->getU32(); const auto& creature = g_map.getCreatureById(creatureId); if (!creature) { @@ -1961,7 +1962,7 @@ void ProtocolGame::parseOpenForge(const InputMessagePtr& msg) const uint16_t fusionCount = msg->getU16(); data.fusionItems.reserve(fusionCount); - for (auto i = 0; i < fusionCount; ++i) { + for (auto i = 0; std::cmp_less(i, fusionCount); ++i) { ForgeItemInfo item; msg->getU8(); // unknown count of friend items item.id = msg->getU16(); @@ -1972,11 +1973,11 @@ void ProtocolGame::parseOpenForge(const InputMessagePtr& msg) const uint16_t convergenceFusionCount = msg->getU16(); data.convergenceFusion.reserve(convergenceFusionCount); - for (auto i = 0; i < convergenceFusionCount; ++i) { + for (auto i = 0; std::cmp_less(i, convergenceFusionCount); ++i) { const uint8_t items = msg->getU8(); std::vector slotItems; slotItems.reserve(items); - for (auto j = 0; j < items; ++j) { + for (auto j = 0; std::cmp_less(j, items); ++j) { ForgeItemInfo item; item.id = msg->getU16(); item.tier = msg->getU8(); @@ -1988,11 +1989,11 @@ void ProtocolGame::parseOpenForge(const InputMessagePtr& msg) const uint8_t transferTotalCount = msg->getU8(); data.transfers.reserve(transferTotalCount); - for (auto i = 0; i < transferTotalCount; ++i) { + for (auto i = 0; std::cmp_less(i, transferTotalCount); ++i) { ForgeTransferData transfer; const uint16_t donorCount = msg->getU16(); transfer.donors.reserve(donorCount); - for (auto j = 0; j < donorCount; ++j) { + for (auto j = 0; std::cmp_less(j, donorCount); ++j) { ForgeItemInfo donor; donor.id = msg->getU16(); donor.tier = msg->getU8(); @@ -2001,7 +2002,7 @@ void ProtocolGame::parseOpenForge(const InputMessagePtr& msg) } const uint16_t receiverCount = msg->getU16(); transfer.receivers.reserve(receiverCount); - for (auto j = 0; j < receiverCount; ++j) { + for (auto j = 0; std::cmp_less(j, receiverCount); ++j) { ForgeItemInfo receiver; receiver.id = msg->getU16(); receiver.count = msg->getU16(); @@ -2013,11 +2014,11 @@ void ProtocolGame::parseOpenForge(const InputMessagePtr& msg) const uint8_t convergenceTransferCount = msg->getU8(); data.convergenceTransfers.reserve(convergenceTransferCount); - for (auto i = 0; i < convergenceTransferCount; ++i) { + for (auto i = 0; std::cmp_less(i, convergenceTransferCount); ++i) { ForgeTransferData transfer; const uint16_t donorCount = msg->getU16(); transfer.donors.reserve(donorCount); - for (auto j = 0; j < donorCount; ++j) { + for (auto j = 0; std::cmp_less(j, donorCount); ++j) { ForgeItemInfo donor; donor.id = msg->getU16(); donor.tier = msg->getU8(); @@ -2026,7 +2027,7 @@ void ProtocolGame::parseOpenForge(const InputMessagePtr& msg) } const uint16_t receiverCount = msg->getU16(); transfer.receivers.reserve(receiverCount); - for (auto j = 0; j < receiverCount; ++j) { + for (auto j = 0; std::cmp_less(j, receiverCount); ++j) { ForgeItemInfo receiver; receiver.id = msg->getU16(); receiver.count = msg->getU16(); @@ -2059,7 +2060,7 @@ void ProtocolGame::addCreatureIcon(const InputMessagePtr& msg, const uint32_t cr const uint8_t sizeIcons = msg->getU8(); std::vector> icons; // icon, category, count - for (auto i = 0; i < sizeIcons; ++i) { + for (auto i = 0; std::cmp_less(i, sizeIcons); ++i) { const uint8_t icon = msg->getU8(); // icon.serialize() const uint8_t category = msg->getU8(); // icon.category -- 0x00 = monster // 0x01 = player? const uint16_t count = msg->getU16(); // icon.count @@ -2247,7 +2248,7 @@ void ProtocolGame::parsePremiumTrigger(const InputMessagePtr& msg) const uint8_t triggerCount = msg->getU8(); std::vector triggers; - for (auto i = 0; i < triggerCount; ++i) { + for (auto i = 0; std::cmp_less(i, triggerCount); ++i) { triggers.push_back(msg->getU8()); } @@ -2273,7 +2274,7 @@ void ProtocolGame::parsePlayerInfo(const InputMessagePtr& msg) const const uint16_t spellCount = msg->getU16(); std::vector spells; - for (auto i = 0; i < spellCount; ++i) { + for (auto i = 0; std::cmp_less(i, spellCount); ++i) { if (g_game.getFeature(Otc::GameUshortSpell)) { spells.push_back(msg->getU16()); // spell id } else { @@ -2435,7 +2436,7 @@ void ProtocolGame::parsePlayerSkills(const InputMessagePtr& msg) const if (g_game.getFeature(Otc::GameForgeSkillStats)) { const uint8_t lastSkill = g_game.getClientVersion() >= 1332 ? Otc::LastSkill : Otc::Momentum + 1; - for (int_fast32_t skill = Otc::Fatal; skill < lastSkill; ++skill) { + for (int_fast32_t skill = Otc::Fatal; std::cmp_less(skill, lastSkill); ++skill) { const uint16_t level = msg->getU16(); const uint16_t baseLevel = msg->getU16(); m_localPlayer->setSkill(static_cast(skill), level, 0); @@ -2487,7 +2488,7 @@ void ProtocolGame::parsePlayerSkills(const InputMessagePtr& msg) const // Combat absorb values const uint8_t combatsCount = msg->getU8(); std::map absorbValues; - for (int i = 0; i < combatsCount; i++) { + for (int i = 0; std::cmp_less(i, combatsCount); i++) { const uint8_t combatType = msg->getU8(); const double value = msg->getDouble(); absorbValues[combatType] = value; @@ -2620,7 +2621,7 @@ void ProtocolGame::parseChannelList(const InputMessagePtr& msg) const uint8_t channelListSize = msg->getU8(); std::vector> channelList; - for (auto i = 0; i < channelListSize; ++i) { + for (auto i = 0; std::cmp_less(i, channelListSize); ++i) { const uint16_t channelId = msg->getU16(); const auto& channelName = msg->getString(); channelList.emplace_back(channelId, channelName); @@ -2636,12 +2637,12 @@ void ProtocolGame::parseOpenChannel(const InputMessagePtr& msg) if (g_game.getFeature(Otc::GameChannelPlayerList)) { const uint16_t joinedPlayers = msg->getU16(); - for (auto i = 0; i < joinedPlayers; ++i) { + for (auto i = 0; std::cmp_less(i, joinedPlayers); ++i) { g_game.formatCreatureName(msg->getString()); // player name } const uint16_t invitedPlayers = msg->getU16(); - for (auto i = 0; i < invitedPlayers; ++i) { + for (auto i = 0; std::cmp_less(i, invitedPlayers); ++i) { g_game.formatCreatureName(msg->getString()); // player name } } @@ -2854,7 +2855,7 @@ void ProtocolGame::parseOpenOutfitWindow(const InputMessagePtr& msg) const if (g_game.getFeature(Otc::GameNewOutfitProtocol)) { const uint16_t outfitCount = g_game.getClientVersion() >= 1281 ? msg->getU16() : msg->getU8(); - for (auto i = 0; i < outfitCount; ++i) { + for (auto i = 0; std::cmp_less(i, outfitCount); ++i) { const uint16_t outfitId = msg->getU16(); const auto& outfitName = msg->getString(); const uint8_t outfitAddons = msg->getU8(); @@ -2888,7 +2889,7 @@ void ProtocolGame::parseOpenOutfitWindow(const InputMessagePtr& msg) const if (g_game.getFeature(Otc::GamePlayerMounts)) { const uint16_t mountCount = g_game.getClientVersion() >= 1281 ? msg->getU16() : msg->getU8(); - for (auto i = 0; i < mountCount; ++i) { + for (auto i = 0; std::cmp_less(i, mountCount); ++i) { const uint16_t mountId = msg->getU16(); // mount type const auto& mountName = msg->getString(); // mount name uint8_t mountMode = 0; @@ -2906,7 +2907,7 @@ void ProtocolGame::parseOpenOutfitWindow(const InputMessagePtr& msg) const std::vector > familiarList; if (g_game.getFeature(Otc::GamePlayerFamiliars)) { const uint16_t familiarCount = msg->getU16(); - for (auto i = 0; i < familiarCount; ++i) { + for (auto i = 0; std::cmp_less(i, familiarCount); ++i) { const uint16_t familiarLookType = msg->getU16(); // familiar lookType const auto& familiarName = msg->getString(); // familiar name const uint8_t familiarMode = msg->getU8(); // 0x00 // mode: 0x00 - available, 0x01 store (requires U32 store offerId) @@ -2930,28 +2931,28 @@ void ProtocolGame::parseOpenOutfitWindow(const InputMessagePtr& msg) const if (g_game.getFeature(Otc::GameWingsAurasEffectsShader)) { const uint8_t wingCount = msg->getU8(); - for (auto i = 0; i < wingCount; ++i) { + for (auto i = 0; std::cmp_less(i, wingCount); ++i) { const uint16_t wingId = msg->getU16(); const auto& wingName = msg->getString(); wingList.emplace_back(wingId, wingName); } const uint8_t auraCount = msg->getU8(); - for (auto i = 0; i < auraCount; ++i) { + for (auto i = 0; std::cmp_less(i, auraCount); ++i) { const uint16_t auraId = msg->getU16(); const auto& auraName = msg->getString(); auraList.emplace_back(auraId, auraName); } const uint8_t effectCount = msg->getU8(); - for (auto i = 0; i < effectCount; ++i) { + for (auto i = 0; std::cmp_less(i, effectCount); ++i) { const uint16_t effectId = msg->getU16(); const auto& effectName = msg->getString(); effectList.emplace_back(effectId, effectName); } const uint8_t shaderCount = msg->getU8(); - for (auto i = 0; i < shaderCount; ++i) { + for (auto i = 0; std::cmp_less(i, shaderCount); ++i) { const uint16_t shaderId = msg->getU16(); const auto& shaderName = msg->getString(); shaderList.emplace_back(shaderId, shaderName); @@ -3008,7 +3009,7 @@ void ProtocolGame::parseKillTracker(const InputMessagePtr& msg) std::vector dropItems; dropItems.reserve(corpseItemsSize); - for (auto i = 0; i < corpseItemsSize; ++i) { + for (auto i = 0; std::cmp_less(i, corpseItemsSize); ++i) { dropItems.push_back(getItem(msg)); } @@ -3035,7 +3036,7 @@ void ProtocolGame::parseVipAdd(const InputMessagePtr& msg) if (g_game.getFeature(Otc::GameVipGroups)) { const uint8_t vipGroupSize = msg->getU8(); groupIDs.reserve(vipGroupSize); - for (auto i = 0; i < vipGroupSize; ++i) { + for (auto i = 0; std::cmp_less(i, vipGroupSize); ++i) { const uint8_t groupID = msg->getU8(); groupIDs.push_back(groupID); } @@ -3058,7 +3059,7 @@ void ProtocolGame::parseVipLogout(const InputMessagePtr& msg) if (g_game.getFeature(Otc::GameVipGroups)) { const uint8_t vipGroupSize = msg->getU8(); std::vector> vipGroups; - for (auto i = 0; i < vipGroupSize; ++i) { + for (auto i = 0; std::cmp_less(i, vipGroupSize); ++i) { const uint8_t groupId = msg->getU8(); const auto& groupName = msg->getString(); const bool canEditGroup = static_cast(msg->getU8()); @@ -3077,7 +3078,7 @@ void ProtocolGame::parseBestiaryRaces(const InputMessagePtr& msg) std::vector bestiaryData; const uint16_t bestiaryRaceLast = msg->getU16(); - for (auto i = 0; i < bestiaryRaceLast; ++i) { + for (auto i = 0; std::cmp_less(i, bestiaryRaceLast); ++i) { CyclopediaBestiaryRace race; race.race = i; race.bestClass = msg->getString(); @@ -3096,7 +3097,7 @@ void ProtocolGame::parseBestiaryOverview(const InputMessagePtr& msg) const uint16_t raceSize = msg->getU16(); std::vector data; - for (auto i = 0; i < raceSize; ++i) { + for (auto i = 0; std::cmp_less(i, raceSize); ++i) { const uint16_t raceId = msg->getU16(); const uint8_t progress = msg->getU8(); uint8_t occurrence = 0; @@ -3146,7 +3147,7 @@ void ProtocolGame::parseBestiaryMonsterData(const InputMessagePtr& msg) data.ocorrence = msg->getU8(); const uint8_t lootCount = msg->getU8(); - for (auto i = 0; i < lootCount; ++i) { + for (auto i = 0; std::cmp_less(i, lootCount); ++i) { LootItem lootItem; lootItem.itemId = msg->getU16(); lootItem.diffculty = msg->getU8(); @@ -3173,7 +3174,7 @@ void ProtocolGame::parseBestiaryMonsterData(const InputMessagePtr& msg) if (data.currentLevel > 2) { const uint8_t elementsCount = msg->getU8(); - for (auto i = 0; i < elementsCount; ++i) { + for (auto i = 0; std::cmp_less(i, elementsCount); ++i) { const uint8_t elementId = msg->getU8(); const uint16_t elementValue = msg->getU16(); data.combat[elementId] = elementValue; @@ -3210,7 +3211,7 @@ void ProtocolGame::parseBestiaryCharmsData(const InputMessagePtr& msg) const uint8_t charmsAmount = msg->getU8(); charmData.charms.reserve(charmsAmount); - for (auto i = 0; i < charmsAmount; ++i) { + for (auto i = 0; std::cmp_less(i, charmsAmount); ++i) { CharmData charm; charm.id = msg->getU8(); charm.asignedStatus = false; @@ -3254,7 +3255,7 @@ void ProtocolGame::parseBestiaryCharmsData(const InputMessagePtr& msg) const uint16_t finishedMonstersSize = msg->getU16(); charmData.finishedMonsters.reserve(finishedMonstersSize); - for (auto i = 0; i < finishedMonstersSize; ++i) { + for (auto i = 0; std::cmp_less(i, finishedMonstersSize); ++i) { uint32_t raceId; if (g_game.getClientVersion() >= 1410) { raceId = msg->getU32(); @@ -3292,7 +3293,7 @@ void ProtocolGame::parseQuestLog(const InputMessagePtr& msg) const uint16_t questsCount = msg->getU16(); std::vector> questList; - for (auto i = 0; i < questsCount; ++i) { + for (auto i = 0; std::cmp_less(i, questsCount); ++i) { const uint16_t id = msg->getU16(); const auto& questName = msg->getString(); const bool questCompleted = static_cast(msg->getU8()); @@ -3309,7 +3310,7 @@ void ProtocolGame::parseQuestLine(const InputMessagePtr& msg) const uint8_t missionCount = msg->getU8(); std::vector> questMissions; - for (auto i = 0; i < missionCount; ++i) { + for (auto i = 0; std::cmp_less(i, missionCount); ++i) { auto missionId = 0; if (g_game.getClientVersion() >= 1200) { missionId = msg->getU16(); @@ -3336,7 +3337,7 @@ void ProtocolGame::parseItemInfo(const InputMessagePtr& msg) const const uint8_t listCount = msg->getU8(); std::vector> itemList; - for (auto i = 0; i < listCount; ++i) { + for (auto i = 0; std::cmp_less(i, listCount); ++i) { const auto& item = std::make_shared(); item->setId(msg->getU16()); item->setCountOrSubType(g_game.getFeature(Otc::GameCountU16) ? msg->getU16() : msg->getU8()); @@ -3350,7 +3351,7 @@ void ProtocolGame::parseItemInfo(const InputMessagePtr& msg) const void ProtocolGame::parsePlayerInventory(const InputMessagePtr& msg) { const uint16_t size = msg->getU16(); - for (auto i = 0; i < size; ++i) { + for (auto i = 0; std::cmp_less(i, size); ++i) { msg->getU16(); // id msg->getU8(); // subtype msg->getU16(); // count @@ -3366,7 +3367,7 @@ void ProtocolGame::parseModalDialog(const InputMessagePtr& msg) const uint8_t buttonsCount = msg->getU8(); std::vector> buttonList; - for (auto i = 0; i < buttonsCount; ++i) { + for (auto i = 0; std::cmp_less(i, buttonsCount); ++i) { const auto& value = msg->getString(); const uint8_t buttonId = msg->getU8(); buttonList.emplace_back(buttonId, value); @@ -3375,7 +3376,7 @@ void ProtocolGame::parseModalDialog(const InputMessagePtr& msg) const uint8_t choicesCount = msg->getU8(); std::vector> choiceList; - for (auto i = 0; i < choicesCount; ++i) { + for (auto i = 0; std::cmp_less(i, choicesCount); ++i) { const auto& value = msg->getString(); const uint8_t choideId = msg->getU8(); choiceList.emplace_back(choideId, value); @@ -3468,7 +3469,7 @@ void ProtocolGame::setMapDescription(const InputMessagePtr& msg, const int x, co int endz; int zstep; - if (z > g_gameConfig.getMapSeaFloor()) { + if (std::cmp_greater(z, g_gameConfig.getMapSeaFloor())) { startz = z - g_gameConfig.getMapAwareUndergroundFloorRange(); endz = std::min(z + g_gameConfig.getMapAwareUndergroundFloorRange(), g_gameConfig.getMapMaxZ()); zstep = 1; @@ -3518,7 +3519,7 @@ int ProtocolGame::setTileDescription(const InputMessagePtr& msg, const Position continue; } - if (stackPos > g_gameConfig.getTileMaxThings()) { + if (std::cmp_greater(stackPos, g_gameConfig.getTileMaxThings())) { g_logger.traceError("ProtocolGame::setTileDescription: too many things, pos={}, stackpos={}", position, stackPos); } @@ -3810,7 +3811,7 @@ CreaturePtr ProtocolGame::getCreature(const InputMessagePtr& msg, int type) cons std::vector attachedEffectList; if (g_game.getFeature(Otc::GameCreatureAttachedEffect)) { const uint8_t listSize = msg->getU8(); - for (auto i = -1; ++i < listSize;) { + for (auto i = -1; std::cmp_less(++i, listSize);) { attachedEffectList.push_back(msg->getU16()); } } @@ -4059,7 +4060,7 @@ void ProtocolGame::parseBestiaryTracker(const InputMessagePtr& msg) const uint8_t size = msg->getU8(); std::vector> trackerData; - for (auto i = 0; i < size; ++i) { + for (auto i = 0; std::cmp_less(i, size); ++i) { const uint16_t raceID = msg->getU16(); const uint32_t killCount = msg->getU32(); const uint16_t firstUnlock = msg->getU16(); @@ -4075,13 +4076,13 @@ void ProtocolGame::parseBestiaryTracker(const InputMessagePtr& msg) void ProtocolGame::parseTaskHuntingBasicData(const InputMessagePtr& msg) { const uint16_t preys = msg->getU16(); - for (auto i = 0; i < preys; ++i) { + for (auto i = 0; std::cmp_less(i, preys); ++i) { msg->getU16(); // RaceID msg->getU8(); // Difficult } const uint8_t options = msg->getU8(); - for (auto i = 0; i < options; ++i) { + for (auto i = 0; std::cmp_less(i, options); ++i) { msg->getU8(); // Difficult msg->getU8(); // Stars msg->getU16(); // First kill @@ -4107,7 +4108,7 @@ void ProtocolGame::parseTaskHuntingData(const InputMessagePtr& msg) case Otc::PREY_TASK_STATE_SELECTION: { const uint16_t creatures = msg->getU16(); - for (auto i = 0; i < creatures; ++i) { + for (auto i = 0; std::cmp_less(i, creatures); ++i) { msg->getU16(); // RaceID msg->getU8(); // Is unlocked } @@ -4116,7 +4117,7 @@ void ProtocolGame::parseTaskHuntingData(const InputMessagePtr& msg) case Otc::PREY_TASK_STATE_LIST_SELECTION: { const uint16_t creatures = msg->getU16(); - for (auto i = 0; i < creatures; ++i) { + for (auto i = 0; std::cmp_less(i, creatures); ++i) { msg->getU16(); // RaceID msg->getU8(); // Is unlocked } @@ -4157,7 +4158,7 @@ void ProtocolGame::parseLootContainers(const InputMessagePtr& msg) const uint8_t containersCount = msg->getU8(); std::vector> lootList; - for (auto i = 0; i < containersCount; ++i) { + for (auto i = 0; std::cmp_less(i, containersCount); ++i) { const uint8_t categoryType = msg->getU8(); const uint16_t lootContainerId = msg->getU16(); uint16_t obtainerContainerId = 0; @@ -4200,7 +4201,7 @@ void ProtocolGame::parseCyclopediaHousesInfo(const InputMessagePtr& msg) msg->getU32(); // houseClientId const uint16_t housesList = msg->getU16(); // g_game().map.houses.getHouses() - for (auto i = 0; i < housesList; ++i) { + for (auto i = 0; std::cmp_less(i, housesList); ++i) { msg->getU32(); // getClientId } // TO-DO Lua // Otui @@ -4209,7 +4210,7 @@ void ProtocolGame::parseCyclopediaHousesInfo(const InputMessagePtr& msg) void ProtocolGame::parseCyclopediaHouseList(const InputMessagePtr& msg) { const uint16_t housesCount = msg->getU16(); // housesCount - for (auto i = 0; i < housesCount; ++i) { + for (auto i = 0; std::cmp_less(i, housesCount); ++i) { msg->getU32(); // clientId msg->getU8(); // 0x00 = Renovation, 0x01 = Available @@ -4290,7 +4291,7 @@ void ProtocolGame::parseSupplyStash(const InputMessagePtr& msg) const uint16_t itemsCount = msg->getU16(); std::vector> stashItems; - for (auto i = 0; i < itemsCount; ++i) { + for (auto i = 0; std::cmp_less(i, itemsCount); ++i) { uint16_t itemId = msg->getU16(); uint32_t amount = msg->getU32(); stashItems.push_back({ itemId, amount }); @@ -4323,14 +4324,14 @@ void ProtocolGame::parsePartyAnalyzer(const InputMessagePtr& msg) const uint8_t partyMembersSize = msg->getU8(); std::vector membersData; - for (auto i = 0; i < partyMembersSize; ++i) { + for (auto i = 0; std::cmp_less(i, partyMembersSize); ++i) { const uint32_t memberID = msg->getU32(); // party member id const uint8_t highlight = msg->getU8(); // highlight const uint64_t loot = msg->getU64(); // loot const uint64_t supply = msg->getU64(); // supply const uint64_t damage = msg->getU64(); // damage const uint64_t healing = msg->getU64(); // healing - + if (shouldExecuteCallback) { membersData.emplace_back(memberID, highlight, loot, supply, damage, healing); } @@ -4340,7 +4341,7 @@ void ProtocolGame::parsePartyAnalyzer(const InputMessagePtr& msg) const bool hasNamesBool = static_cast(msg->getU8()); if (hasNamesBool) { const uint8_t membersNameSize = msg->getU8(); - for (auto i = 0; i < membersNameSize; ++i) { + for (auto i = 0; std::cmp_less(i, membersNameSize); ++i) { const uint32_t memberID = msg->getU32(); // party member id const std::string memberName = msg->getString(); // party member name if (shouldExecuteCallback) { @@ -4361,7 +4362,7 @@ void ProtocolGame::parseImbuementDurations(const InputMessagePtr& msg) const uint8_t itemListCount = msg->getU8(); // amount of items to display std::vector itemList; - for (auto i = 0; i < itemListCount; ++i) { + for (auto i = 0; std::cmp_less(i, itemListCount); ++i) { ImbuementTrackerItem item(msg->getU8()); // slot item.item = getItem(msg); @@ -4374,7 +4375,7 @@ void ProtocolGame::parseImbuementDurations(const InputMessagePtr& msg) continue; } - for (auto slotIndex = 0; slotIndex < slotsCount; ++slotIndex) { + for (auto slotIndex = 0; std::cmp_less(slotIndex, slotsCount); ++slotIndex) { const bool slotImbued = static_cast(msg->getU8()); // 0 - empty, 1 - imbued if (!slotImbued) { continue; @@ -4431,7 +4432,7 @@ void ProtocolGame::parseBlessDialog(const InputMessagePtr& msg) BlessDialogData data; data.totalBless = msg->getU8(); - for (auto i = 0; i < data.totalBless; ++i) { + for (auto i = 0; std::cmp_less(i, data.totalBless); ++i) { BlessData bless{}; bless.blessBitwise = msg->getU16(); bless.playerBlessCount = msg->getU8(); @@ -4450,7 +4451,7 @@ void ProtocolGame::parseBlessDialog(const InputMessagePtr& msg) data.aol = msg->getU8(); const uint8_t logCount = msg->getU8(); - for (auto i = 0; i < logCount; ++i) { + for (auto i = 0; std::cmp_less(i, logCount); ++i) { LogData log; log.timestamp = msg->getU32(); log.colorMessage = msg->getU8(); @@ -4474,17 +4475,17 @@ void ProtocolGame::parseUpdateImpactTracker(const InputMessagePtr& msg) { const uint8_t analyzerType = msg->getU8(); const uint32_t amount = msg->getU32(); - + uint8_t effect = 0; // Default effect for healing std::string target = ""; // Default empty target - + if (analyzerType == 1) { // ANALYZER_DAMAGE_DEALT effect = msg->getU8(); // Element/combat type } else if (analyzerType == 2) { // ANALYZER_DAMAGE_RECEIVED effect = msg->getU8(); // Element/combat type target = msg->getString(); // Target name } - + // Call the onImpactTracker callback to expose the data to Lua g_lua.callGlobalField("g_game", "onImpactTracker", analyzerType, amount, effect, target); } @@ -4493,7 +4494,7 @@ void ProtocolGame::parseItemsPrice(const InputMessagePtr& msg) { const uint16_t priceCount = msg->getU16(); // count - for (auto i = 0; i < priceCount; ++i) { + for (auto i = 0; std::cmp_less(i, priceCount); ++i) { const uint16_t itemId = msg->getU16(); // item client id if (g_game.getClientVersion() >= 1281) { const auto& item = Item::create(itemId); @@ -4612,7 +4613,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) const uint8_t combatCount = msg->getU8(); std::vector> combats; - for (auto i = 0; i < combatCount; ++i) { + for (auto i = 0; std::cmp_less(i, combatCount); ++i) { const uint8_t element = msg->getU8(); const uint16_t specializedMagicLevel = msg->getU16(); combats.emplace_back(element, specializedMagicLevel); @@ -4680,7 +4681,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) const uint8_t combatCount = msg->getU8(); std::vector> combatsArray; - for (auto i = 0; i < combatCount; ++i) { + for (auto i = 0; std::cmp_less(i, combatCount); ++i) { const uint8_t element = msg->getU8(); const uint16_t clientModifier = msg->getU16(); combatsArray.emplace_back(element, clientModifier); @@ -4689,7 +4690,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) const uint8_t concoctionsCount = msg->getU8(); std::vector> concoctionsArray; - for (auto i = 0; i < concoctionsCount; ++i) { + for (auto i = 0; std::cmp_less(i, concoctionsCount); ++i) { const uint16_t concoctionFirst = msg->getU16(); const uint16_t concoctionSecond = msg->getU16(); concoctionsArray.emplace_back(concoctionFirst, concoctionSecond); @@ -4705,7 +4706,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) msg->getU16(); const uint16_t entriesCount = msg->getU16(); - for (auto i = 0; i < entriesCount; ++i) { + for (auto i = 0; std::cmp_less(i, entriesCount); ++i) { RecentDeathEntry entry; entry.timestamp = msg->getU32(); entry.cause = msg->getString(); @@ -4722,7 +4723,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) msg->getU16(); const uint16_t entriesCount = msg->getU16(); - for (auto i = 0; i < entriesCount; ++i) { + for (auto i = 0; std::cmp_less(i, entriesCount); ++i) { RecentPvPKillEntry entry; entry.timestamp = msg->getU32(); entry.description = msg->getString(); @@ -4742,7 +4743,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) CyclopediaCharacterItemSummary data; const uint16_t inventoryItemsCount = msg->getU16(); - for (auto i = 0; i < inventoryItemsCount; ++i) { + for (auto i = 0; std::cmp_less(i, inventoryItemsCount); ++i) { ItemSummary item; const uint16_t itemId = msg->getU16(); const auto& itemCreated = Item::create(itemId); @@ -4760,7 +4761,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) } const uint16_t storeItemsCount = msg->getU16(); - for (auto i = 0; i < storeItemsCount; ++i) { + for (auto i = 0; std::cmp_less(i, storeItemsCount); ++i) { ItemSummary item; const uint16_t itemId = msg->getU16(); const auto& itemCreated = Item::create(itemId); @@ -4778,7 +4779,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) } const uint16_t stashItemsCount = msg->getU16(); - for (auto i = 0; i < stashItemsCount; ++i) { + for (auto i = 0; std::cmp_less(i, stashItemsCount); ++i) { ItemSummary item; const uint16_t itemId = msg->getU16(); const auto& thing = g_things.getThingType(itemId, ThingCategoryItem); @@ -4799,7 +4800,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) } const uint16_t depotItemsCount = msg->getU16(); - for (auto i = 0; i < depotItemsCount; ++i) { + for (auto i = 0; std::cmp_less(i, depotItemsCount); ++i) { ItemSummary item; const uint16_t itemId = msg->getU16(); const auto& itemCreated = Item::create(itemId); @@ -4817,7 +4818,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) } const uint16_t inboxItemsCount = msg->getU16(); - for (auto i = 0; i < inboxItemsCount; ++i) { + for (auto i = 0; std::cmp_less(i, inboxItemsCount); ++i) { ItemSummary item; const uint16_t itemId = msg->getU16(); const auto& itemCreated = Item::create(itemId); @@ -4842,7 +4843,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) const uint16_t outfitsSize = msg->getU16(); std::vector outfits; - for (auto i = 0; i < outfitsSize; ++i) { + for (auto i = 0; std::cmp_less(i, outfitsSize); ++i) { CharacterInfoOutfits outfit; outfit.lookType = msg->getU16(); outfit.name = msg->getString(); @@ -4863,7 +4864,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) const uint16_t mountsSize = msg->getU16(); std::vector mounts; - for (auto i = 0; i < mountsSize; ++i) { + for (auto i = 0; std::cmp_less(i, mountsSize); ++i) { CharacterInfoMounts mount; mount.mountId = msg->getU16(); mount.name = msg->getString(); @@ -4882,7 +4883,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) const uint16_t familiarsSize = msg->getU16(); std::vector familiars; - for (auto i = 0; i < familiarsSize; ++i) { + for (auto i = 0; std::cmp_less(i, familiarsSize); ++i) { CharacterInfoFamiliar familiar; familiar.lookType = msg->getU16(); familiar.name = msg->getString(); @@ -4902,7 +4903,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) std::vector> blessings; const uint8_t blessingCount = msg->getU8(); - for (auto i = 0; i < blessingCount; ++i) { + for (auto i = 0; std::cmp_less(i, blessingCount); ++i) { const auto& blessingName = msg->getString(); const uint8_t blessingObtained = msg->getU8(); blessings.emplace_back(blessingName, blessingObtained); @@ -4917,7 +4918,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) std::vector hirelingSkills; const uint8_t hirelingSkillsCount = msg->getU8(); - for (auto i = 0; i < hirelingSkillsCount; ++i) { + for (auto i = 0; std::cmp_less(i, hirelingSkillsCount); ++i) { const uint8_t skill = msg->getU8(); hirelingSkills.emplace_back(static_cast(skill + 1000)); } @@ -4927,7 +4928,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) std::vector> houseItems; const uint16_t houseItemsCount = msg->getU16(); - for (auto i = 0; i < houseItemsCount; ++i) { + for (auto i = 0; std::cmp_less(i, houseItemsCount); ++i) { const uint16_t itemId = msg->getU16(); const auto& itemName = msg->getString(); const uint8_t count = msg->getU8(); @@ -4950,7 +4951,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) const uint8_t badgesSize = msg->getU8(); std::vector> badgesVector; - for (auto i = 0; i < badgesSize; ++i) { + for (auto i = 0; std::cmp_less(i, badgesSize); ++i) { const uint32_t badgeId = msg->getU32(); const auto& badgeName = msg->getString(); badgesVector.emplace_back(badgeId, badgeName); @@ -4963,7 +4964,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) { msg->getU8(); // current title const uint8_t titlesSize = msg->getU8(); - for (auto i = 0; i < titlesSize; ++i) { + for (auto i = 0; std::cmp_less(i, titlesSize); ++i) { msg->getString(); // title name msg->getString(); // title description msg->getU8(); // bool title permanent @@ -5029,7 +5030,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) data.weaponElementType = msg->getU8(); const uint8_t accuracyCount = msg->getU8(); - for (int i = 0; i < accuracyCount; i++) { + for (int i = 0; std::cmp_less(i, accuracyCount); i++) { msg->getU8(); // range data.weaponAccuracy.push_back(msg->getDouble()); } @@ -5068,7 +5069,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) data.mitigationWheel = msg->getDouble(); data.mitigationCombatTactics = msg->getDouble(); const uint8_t combatsCount = msg->getU8(); - for (int i = 0; i < combatsCount; ++i) { + for (int i = 0; std::cmp_less(i, combatsCount); ++i) { uint8_t elementType = msg->getU8(); if (elementType == 0x04) { CyclopediaCharacterDefenceStats::ElementalResistance resistance; @@ -5104,7 +5105,7 @@ void ProtocolGame::parseCyclopediaCharacterInfo(const InputMessagePtr& msg) data.totalBlesses = msg->getU8(); const uint8_t concoctionsCount = msg->getU8(); - for (int i = 0; i < concoctionsCount; ++i) { + for (int i = 0; std::cmp_less(i, concoctionsCount); ++i) { CyclopediaCharacterMiscStats::Concoction concoction; concoction.id = msg->getU16(); msg->getU8(); // unused @@ -5166,7 +5167,7 @@ namespace { // select x items from the list day.itemsToSelect = msg->getU8(); // reward type const uint8_t itemListSize = msg->getU8(); - for (auto listIndex = 0; listIndex < itemListSize; ++listIndex) { + for (auto listIndex = 0; std::cmp_less(listIndex, itemListSize); ++listIndex) { DailyRewardItem item; item.itemId = msg->getU16(); // Item ID item.name = msg->getString(); // Item name @@ -5176,7 +5177,7 @@ namespace { } else if (day.redeemMode == 2) { // no choice, click to redeem all const uint8_t itemListSize = msg->getU8(); - for (auto listIndex = 0; listIndex < itemListSize; ++listIndex) { + for (auto listIndex = 0; std::cmp_less(listIndex, itemListSize); ++listIndex) { const uint8_t bundleType = msg->getU8(); // type of reward DailyRewardBundle bundle; bundle.bundleType = bundleType; @@ -5220,13 +5221,13 @@ void ProtocolGame::parseDailyReward(const InputMessagePtr& msg) DailyRewardData data; data.days = msg->getU8(); // Reward count (7 days) - for (auto i = 1; i <= data.days; ++i) { + for (auto i = 1; std::cmp_less_equal(i, data.days); ++i) { data.freeRewards.push_back(parseRewardDay(msg)); // Free account data.premiumRewards.push_back(parseRewardDay(msg)); // Premium account } const uint8_t bonusCount = msg->getU8(); - for (auto i = 0; i < bonusCount; ++i) { + for (auto i = 0; std::cmp_less(i, bonusCount); ++i) { DailyRewardBonus bonus; bonus.name = msg->getString(); // Bonus name bonus.id = msg->getU8(); // Bonus ID @@ -5242,7 +5243,7 @@ void ProtocolGame::parseRewardHistory(const InputMessagePtr& msg) { const uint8_t historyCount = msg->getU8(); std::vector> rewardHistory; - for (auto i = 0; i < historyCount; ++i) { + for (auto i = 0; std::cmp_less(i, historyCount); ++i) { const uint32_t timestamp = msg->getU32(); const bool isPremium = static_cast(msg->getU8()); const auto& description = msg->getString(); @@ -5281,7 +5282,7 @@ std::vector ProtocolGame::getPreyMonsters(const InputMessagePtr& ms const uint8_t monsterListCount = msg->getU8(); std::vector monsterList; - for (auto i = 0; i < monsterListCount; ++i) { + for (auto i = 0; std::cmp_less(i, monsterListCount); ++i) { const auto& monster = getPreyMonster(msg); monsterList.emplace_back(monster); } @@ -5384,7 +5385,7 @@ void ProtocolGame::parsePreyData(const InputMessagePtr& msg) const uint16_t raceListCount = msg->getU16(); std::vector raceList; - for (auto i = 0; i < raceListCount; ++i) { + for (auto i = 0; std::cmp_less(i, raceListCount); ++i) { raceList.push_back(msg->getU16()); // RaceID } @@ -5405,7 +5406,7 @@ void ProtocolGame::parsePreyData(const InputMessagePtr& msg) const uint16_t raceListCount = msg->getU16(); std::vector raceList; - for (auto i = 0; i < raceListCount; ++i) { + for (auto i = 0; std::cmp_less(i, raceListCount); ++i) { raceList.push_back(msg->getU16()); // RaceID } @@ -5450,7 +5451,7 @@ Imbuement ProtocolGame::getImbuementInfo(const InputMessagePtr& msg) imbuement.premiumOnly = msg->getU8(); // is premium const uint8_t itemsSize = msg->getU8(); // items size - for (auto i = 0; i < itemsSize; ++i) { + for (auto i = 0; std::cmp_less(i, itemsSize); ++i) { const uint16_t id = msg->getU16(); // item client ID const auto& description = msg->getString(); // item name const uint16_t count = msg->getU16(); // count @@ -5486,7 +5487,7 @@ void ProtocolGame::parseImbuementWindow(const InputMessagePtr& msg) const uint8_t slot = msg->getU8(); std::unordered_map> activeSlots; - for (auto i = 0; i < slot; i++) { + for (auto i = 0; std::cmp_less(i, slot); i++) { const uint8_t firstByte = msg->getU8(); if (firstByte == 0x01) { Imbuement imbuement = getImbuementInfo(msg); @@ -5499,7 +5500,7 @@ void ProtocolGame::parseImbuementWindow(const InputMessagePtr& msg) const uint16_t imbuementsSize = msg->getU16(); std::vector imbuements; - for (auto i = 0; i < imbuementsSize; ++i) { + for (auto i = 0; std::cmp_less(i, imbuementsSize); ++i) { imbuements.push_back(getImbuementInfo(msg)); } @@ -5537,7 +5538,7 @@ void ProtocolGame::parseMarketEnter(const InputMessagePtr& msg) const uint16_t itemsSentCount = msg->getU16(); std::vector> depotItems; - for (auto i = 0; i < itemsSentCount; ++i) { + for (auto i = 0; std::cmp_less(i, itemsSentCount); ++i) { const uint16_t itemId = msg->getU16(); uint8_t itemTier = 0; const auto& thing = g_things.getThingType(itemId, ThingCategoryItem); @@ -5564,7 +5565,7 @@ void ProtocolGame::parseMarketEnterOld(const InputMessagePtr& msg) const uint16_t itemsSent = msg->getU16(); std::vector> depotItems; - for (auto i = 0; i < itemsSent; ++i) { + for (auto i = 0; std::cmp_less(i, itemsSent); ++i) { const uint16_t itemId = msg->getU16(); const uint16_t count = msg->getU16(); depotItems.push_back({ itemId, count }); @@ -5620,7 +5621,7 @@ void ProtocolGame::parseMarketDetail(const InputMessagePtr& msg) const uint8_t purchaseStatsListCount = msg->getU8(); std::vector> purchaseStatsList; - for (auto i = 0; i < purchaseStatsListCount; ++i) { + for (auto i = 0; std::cmp_less(i, purchaseStatsListCount); ++i) { uint32_t transactions = msg->getU32(); uint64_t totalPrice = 0; uint64_t highestPrice = 0; @@ -5642,7 +5643,7 @@ void ProtocolGame::parseMarketDetail(const InputMessagePtr& msg) const uint8_t saleStatsListCount = msg->getU8(); std::vector> saleStatsList; - for (auto i = 0; i < saleStatsListCount; ++i) { + for (auto i = 0; std::cmp_less(i, saleStatsListCount); ++i) { const uint32_t transactions = msg->getU32(); uint64_t totalPrice = 0; uint64_t highestPrice = 0; @@ -5816,7 +5817,7 @@ void ProtocolGame::parseBosstiarySlots(const InputMessagePtr& msg) data.bossesUnlocked = msg->getU8(); if (data.bossesUnlocked) { const uint16_t bossesUnlockedSize = msg->getU16(); - for (auto i = 0; i < bossesUnlockedSize; ++i) { + for (auto i = 0; std::cmp_less(i, bossesUnlockedSize); ++i) { BossUnlocked boss; boss.bossId = msg->getU32(); boss.bossRace = msg->getU8(); @@ -5831,14 +5832,14 @@ void ProtocolGame::parseBosstiaryCooldownTimer(const InputMessagePtr& msg) { const uint16_t bossesOnTrackerSize = msg->getU16(); std::vector cooldownData; - - for (auto i = 0; i < bossesOnTrackerSize; ++i) { + + for (auto i = 0; std::cmp_less(i, bossesOnTrackerSize); ++i) { const uint32_t bossRaceId = msg->getU32(); // bossRaceId const uint64_t cooldownTime = msg->getU64(); // Boss cooldown in seconds - + cooldownData.emplace_back(bossRaceId, cooldownTime); } - + // Call the Lua callback with the cooldown data g_lua.callGlobalField("g_game", "onBossCooldown", cooldownData); } @@ -5928,7 +5929,7 @@ void ProtocolGame::parseCreatureTyping(const InputMessagePtr& msg) void ProtocolGame::parseFeatures(const InputMessagePtr& msg) { const uint16_t features = msg->getU16(); - for (auto i = 0; i < features; ++i) { + for (auto i = 0; std::cmp_less(i, features); ++i) { const auto feature = static_cast(msg->getU8()); const auto enabled = static_cast(msg->getU8()); if (enabled) { @@ -5969,7 +5970,7 @@ void ProtocolGame::parseHighscores(const InputMessagePtr& msg) const uint8_t sizeCategories = msg->getU8(); std::vector> categories; - for (auto i = 0; i < sizeCategories; ++i) { + for (auto i = 0; std::cmp_less(i, sizeCategories); ++i) { const uint8_t id = msg->getU8(); const auto& categoryName = msg->getString(); categories.emplace_back(id, categoryName); @@ -5982,7 +5983,7 @@ void ProtocolGame::parseHighscores(const InputMessagePtr& msg) const uint8_t sizeEntries = msg->getU8(); std::vector> highscores; - for (auto i = 0; i < sizeEntries; ++i) { + for (auto i = 0; std::cmp_less(i, sizeEntries); ++i) { const uint32_t rank = msg->getU32(); const auto& name = msg->getString(); const auto& title = msg->getString(); diff --git a/src/client/protocolgamesend.cpp b/src/client/protocolgamesend.cpp index fa6bc039b4..8d639a060b 100644 --- a/src/client/protocolgamesend.cpp +++ b/src/client/protocolgamesend.cpp @@ -704,7 +704,7 @@ void ProtocolGame::sendPartyAnalyzerAction(const uint8_t action, const std::vect const auto& msg = std::make_shared(); msg->addU8(Proto::ClientPartyAnalyzerAction); // 43 msg->addU8(action); - + // Only add items data for PARTYANALYZERACTION_PRICEVALUE (action 3) if (action == 3) { // PARTYANALYZERACTION_PRICEVALUE msg->addU16(static_cast(items.size())); @@ -713,7 +713,7 @@ void ProtocolGame::sendPartyAnalyzerAction(const uint8_t action, const std::vect msg->addU64(price); } } - + send(msg); } @@ -1214,7 +1214,7 @@ void ProtocolGame::sendRequestStoreOffers(const std::string_view categoryName, c send(msg); } -void ProtocolGame::sendRequestStoreHome() +void ProtocolGame::sendRequestStoreHome() { const auto& msg = std::make_shared(); msg->addU8(Proto::ClientRequestStoreOffers); @@ -1521,4 +1521,4 @@ void ProtocolGame::openContainerQuickLoot(const uint8_t action, const uint8_t ca msg->addU8(category); } send(msg); -} +} \ No newline at end of file diff --git a/src/client/spriteappearances.h b/src/client/spriteappearances.h index c1912b21dd..3b85b32e74 100644 --- a/src/client/spriteappearances.h +++ b/src/client/spriteappearances.h @@ -89,12 +89,12 @@ class SpriteAppearances void unload(); void setSpritesCount(const int count) { m_spritesCount = count; } - int getSpritesCount() const { return m_spritesCount; } + [[nodiscard]] int getSpritesCount() const { return m_spritesCount; } void setPath(const std::string& path) { m_path = path; } - std::string getPath() const { return m_path; } + [[nodiscard]] std::string getPath() const { return m_path; } - bool loadSpriteSheet(const SpriteSheetPtr& sheet) const; + [[nodiscard]] bool loadSpriteSheet(const SpriteSheetPtr& sheet) const; void saveSheetToFileBySprite(int id, const std::string& file); void saveSheetToFile(const SpriteSheetPtr& sheet, const std::string& file); SpriteSheetPtr getSheetBySpriteId(int id, bool load = true) { diff --git a/src/client/spritemanager.h b/src/client/spritemanager.h index c46b7db890..7909f70862 100644 --- a/src/client/spritemanager.h +++ b/src/client/spritemanager.h @@ -38,10 +38,10 @@ class FileMetadata spriteId = std::stoi(fileName); } - uint32_t getSpriteId() const { return spriteId; } - const std::string& getFileName() const { return fileName; } - uint32_t getOffset() const { return offset; } - uint32_t getFileSize() const { return fileSize; } + [[nodiscard]] uint32_t getSpriteId() const { return spriteId; } + [[nodiscard]] const std::string& getFileName() const { return fileName; } + [[nodiscard]] uint32_t getOffset() const { return offset; } + [[nodiscard]] uint32_t getFileSize() const { return fileSize; } private: std::string fileName; uint32_t offset = 0; @@ -94,7 +94,8 @@ class SpriteManager }; void load(); - FileStreamPtr getSpriteFile() const { + + [[nodiscard]] FileStreamPtr getSpriteFile() const { return m_spritesFiles[0]->file; } diff --git a/src/client/thing.cpp b/src/client/thing.cpp index 28c7c93034..fe60beb226 100644 --- a/src/client/thing.cpp +++ b/src/client/thing.cpp @@ -78,7 +78,7 @@ ContainerPtr Thing::getParentContainer() int Thing::getStackPos() { - if (m_position.x == UINT16_MAX && isItem()) // is inside a container + if (std::cmp_equal(m_position.x, UINT16_MAX) && isItem()) // is inside a container return m_position.z; if (m_stackPos >= 0) diff --git a/src/client/thingtype.cpp b/src/client/thingtype.cpp index d62e81fa42..ac1a711286 100644 --- a/src/client/thingtype.cpp +++ b/src/client/thingtype.cpp @@ -490,7 +490,7 @@ void ThingType::unserialize(const uint16_t clientId, const ThingCategory categor std::vector sizes; std::vector total_sprites; - for (int i = 0; i < groupCount; ++i) { + for (int i = 0; std::cmp_less(i, groupCount); ++i) { uint8_t frameGroupType = FrameGroupDefault; if (hasFrameGroups) frameGroupType = fin->getU8(); @@ -616,7 +616,7 @@ void ThingType::draw(const Point& dest, const int layer, const int xPattern, con if (m_null) return; - if (animationPhase >= m_animationPhases) + if (std::cmp_greater_equal(animationPhase, m_animationPhases)) return; TexturePtr texture; @@ -676,7 +676,7 @@ const TexturePtr& ThingType::getTexture(const int animationPhase) m_loading = true; auto action = [this] { - for (int_fast8_t i = -1; ++i < m_animationPhases;) + for (int_fast8_t i = -1; std::cmp_less(++i, m_animationPhases);) loadTexture(i); m_loading = false; }; @@ -711,9 +711,9 @@ void ThingType::loadTexture(const int animationPhase) static Color maskColors[] = { Color::red, Color::green, Color::blue, Color::yellow }; textureData.pos.resize(indexSize); - for (int z = 0; z < m_numPatternZ; ++z) { - for (int y = 0; y < m_numPatternY; ++y) { - for (int x = 0; x < m_numPatternX; ++x) { + for (int z = 0; std::cmp_less(z, m_numPatternZ); ++z) { + for (int y = 0; std::cmp_less(y, m_numPatternY); ++y) { + for (int x = 0; std::cmp_less(x, m_numPatternX); ++x) { for (int l = 0; l < numLayers; ++l) { const bool spriteMask = m_category == ThingCategoryCreature && l > 0; const int frameIndex = getTextureIndex(l % textureLayers, x, y, z); @@ -825,8 +825,8 @@ Size ThingType::getBestTextureDimension(int w, int h, const int count) assert(h <= g_gameConfig.getSpriteSize()); Size bestDimension = { g_gameConfig.getSpriteSize() }; - for (int i = w; i <= g_gameConfig.getSpriteSize(); i <<= 1) { - for (int j = h; j <= g_gameConfig.getSpriteSize(); j <<= 1) { + for (int i = w; std::cmp_less_equal(i, g_gameConfig.getSpriteSize()); i <<= 1) { + for (int j = h; std::cmp_less_equal(j, g_gameConfig.getSpriteSize()); j <<= 1) { Size candidateDimension = { i, j }; if (candidateDimension.area() < numSprites) continue; diff --git a/src/client/thingtypemanager.h b/src/client/thingtypemanager.h index f7b296dee5..fad098fbab 100644 --- a/src/client/thingtypemanager.h +++ b/src/client/thingtypemanager.h @@ -82,7 +82,7 @@ class ThingTypeManager uint16_t getContentRevision() { return m_contentRevision; } bool isDatLoaded() { return m_datLoaded; } - bool isValidDatId(const uint16_t id, const ThingCategory category) const { return id >= 1 && id < m_thingTypes[category].size(); } + [[nodiscard]] bool isValidDatId(const uint16_t id, const ThingCategory category) const { return id >= 1 && id < m_thingTypes[category].size(); } private: ThingTypeList m_thingTypes[ThingLastCategory]; diff --git a/src/client/tile.cpp b/src/client/tile.cpp index d15e525078..1b37222fab 100644 --- a/src/client/tile.cpp +++ b/src/client/tile.cpp @@ -303,12 +303,12 @@ void Tile::addThing(const ThingPtr& thing, int stackPos) append = !append; } - for (stackPos = 0; stackPos < size; ++stackPos) { + for (stackPos = 0; std::cmp_less(stackPos, size); ++stackPos) { const int otherPriority = m_things[stackPos]->getStackPriority(); if ((append && otherPriority > priority) || (!append && otherPriority >= priority)) break; } - } else if (stackPos > static_cast(size)) + } else if (std::cmp_greater(stackPos, size)) stackPos = size; markHighlightedThing(Color::white); @@ -381,7 +381,7 @@ bool Tile::removeThing(const ThingPtr thing) ThingPtr Tile::getThing(const int stackPos) { - if (stackPos >= 0 && stackPos < static_cast(m_things.size())) + if (stackPos >= 0 && std::cmp_less(stackPos, m_things.size())) return m_things[stackPos]; return nullptr; @@ -643,7 +643,7 @@ bool Tile::isCompletelyCovered(const uint8_t firstFloor, const bool resetCache) bool Tile::isCovered(const int8_t firstFloor) { - if (m_position.z == 0 || m_position.z == firstFloor) return false; + if (m_position.z == 0 || std::cmp_equal(m_position.z, firstFloor)) return false; const uint32_t idChecked = 1 << firstFloor; const uint32_t idState = 1 << (firstFloor + g_gameConfig.getMapMaxZ()); diff --git a/src/client/tile.h b/src/client/tile.h index 14b61c0aea..413c6d71c7 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -183,7 +183,7 @@ class Tile final : public AttachableObject ; } - bool hasElevation(const int elevation = 1) { return m_elevation >= elevation; } + bool hasElevation(const int elevation = 1) { return std::cmp_greater_equal(m_elevation, elevation); } #ifdef FRAMEWORK_EDITOR void overwriteMinimapColor(uint8_t color) { m_minimapColor = color; } diff --git a/src/client/towns.cpp b/src/client/towns.cpp index d3841279a4..6fa64c39e8 100644 --- a/src/client/towns.cpp +++ b/src/client/towns.cpp @@ -23,8 +23,6 @@ #ifdef FRAMEWORK_EDITOR #include "towns.h" -#include - TownManager g_towns; Town::Town(uint32_t tid, std::string name, const Position& pos) : m_id(tid), m_name(std::move(name)) diff --git a/src/client/uigraph.cpp b/src/client/uigraph.cpp index f36214f5e3..2a89ed008a 100644 --- a/src/client/uigraph.cpp +++ b/src/client/uigraph.cpp @@ -89,7 +89,7 @@ void UIGraph::drawSelf(const DrawPoolType drawPane) m_font->drawText(m_title, dest, Color::lightGray, Fw::AlignTopCenter); if (m_showLabes) { const float rotationAngle = -1.5707963267948966f; - + g_drawPool.pushTransformMatrix(); Point maxPoint(dest.left() - 10, dest.top() + 0); g_drawPool.rotate(maxPoint, rotationAngle); @@ -104,7 +104,7 @@ void UIGraph::drawSelf(const DrawPoolType drawPane) m_font->drawText(m_maxValue, Rect(maxRect.x() + 1, maxRect.y(), maxRect.width(), maxRect.height()), Color(0, 0, 0, 150), Fw::AlignCenter); m_font->drawText(m_maxValue, maxRect, Color::lightGray, Fw::AlignCenter); g_drawPool.popTransformMatrix(); - + g_drawPool.pushTransformMatrix(); Point minPoint(dest.left() - 10, dest.bottom() - 0); g_drawPool.rotate(minPoint, rotationAngle); @@ -119,7 +119,7 @@ void UIGraph::drawSelf(const DrawPoolType drawPane) m_font->drawText(m_minValue, Rect(minRect.x() + 1, minRect.y(), minRect.width(), minRect.height()), Color(0, 0, 0, 150), Fw::AlignCenter); m_font->drawText(m_minValue, minRect, Color::lightGray, Fw::AlignCenter); g_drawPool.popTransformMatrix(); - + g_drawPool.pushTransformMatrix(); Point avgPoint(dest.left() - 10, dest.verticalCenter()); g_drawPool.rotate(avgPoint, rotationAngle); @@ -295,7 +295,7 @@ void UIGraph::cacheGraphs() float minValue = 0.0f; float maxValue = 1.0f; bool hasValues = false; - + for (auto& graph : m_graphs) { if (graph.values.empty()) continue; @@ -327,7 +327,7 @@ void UIGraph::cacheGraphs() } if (!m_graphs[0].values.empty()) { m_lastValue = formatNumber(m_graphs[0].values.back()); - + // Calculate average from all values in the first graph float sum = 0.0f; for (const auto& value : m_graphs[0].values) { @@ -503,7 +503,7 @@ std::string UIGraph::formatNumber(const int value) const int absValue = std::abs(value); const bool isNegative = value < 0; const std::string prefix = isNegative ? "-" : ""; - + if (absValue >= 1000000) { // Values 1,000,000+ use KK notation with max 1 decimal for maximum compactness // Example: 1,500,000 = 1.5KK, 5,000,000 = 5KK, 28,424,000 = 28.4KK diff --git a/src/client/uimapanchorlayout.h b/src/client/uimapanchorlayout.h index 4e6cdf3c24..608faf1f4c 100644 --- a/src/client/uimapanchorlayout.h +++ b/src/client/uimapanchorlayout.h @@ -25,8 +25,6 @@ #include "declarations.h" #include -#include - class UIPositionAnchor final : public UIAnchor { public: diff --git a/src/framework/config.h b/src/framework/config.h index 53d29f8130..08ea7788db 100644 --- a/src/framework/config.h +++ b/src/framework/config.h @@ -24,17 +24,29 @@ #include // APPEARANCES -#define BYTES_IN_SPRITE_SHEET 384 * 384 * 4 +enum +{ + BYTES_IN_SPRITE_SHEET = 384 * 384 * 4 +}; + #define LZMA_UNCOMPRESSED_SIZE BYTES_IN_SPRITE_SHEET + 122 #define LZMA_HEADER_SIZE LZMA_PROPS_SIZE + 8 -#define SPRITE_SHEET_WIDTH_BYTES 384 * 4 + +enum +{ + SPRITE_SHEET_WIDTH_BYTES = 384 * 4 +}; // ENCRYPTION SYSTEM // Enable client encryption -#define ENABLE_ENCRYPTION 0 -// Enable client encryption maker/builder. +enum +{ + ENABLE_ENCRYPTION = 0, + // Enable client encryption maker/builder. // You can compile it once and use this executable to only encrypt client files once with command --encrypt which will be using password below. -#define ENABLE_ENCRYPTION_BUILDER 0 +ENABLE_ENCRYPTION_BUILDER = 0 +}; + // for security reasons make sure you are using password with at last 100+ characters #define ENCRYPTION_PASSWORD AY_OBFUSCATE("SET_YOUR_PASSWORD_HERE") // do not insert special characters in the header (ONLY UPPERCASE LETTERS, LOWERCASE LETTERS AND NUMBERS) | example: #define ENCRYPTION_HEADER AY_OBFUSCATE("21UsO5ARfRnIScs415BNMab") @@ -43,13 +55,17 @@ // DISCORD RPC (https://discord.com/developers/applications) // Enable Discord Rich Presence #ifndef ENABLE_DISCORD_RPC - #define ENABLE_DISCORD_RPC 0 // 1 to enable | 0 to disable +#define ENABLE_DISCORD_RPC 0 // 1 to enable | 0 to disable #endif #define RPC_API_KEY "1060650448522051664" // Your API Key // RPC Configs (https://youtu.be/zCHYtRlD58g) step by step to config your rich presence -#define SHOW_CHARACTER_NAME_RPC 1 // 1 to enable | 0 to disable -#define SHOW_CHARACTER_LEVEL_RPC 1 // 1 to enable | 0 to disable -#define SHOW_CHARACTER_WORLD_RPC 1 // 1 to enable | 0 to disable +enum +{ + SHOW_CHARACTER_NAME_RPC = 1, // 1 to enable | 0 to disable + SHOW_CHARACTER_LEVEL_RPC = 1, // 1 to enable | 0 to disable + SHOW_CHARACTER_WORLD_RPC = 1 // 1 to enable | 0 to disable +}; + #define OFFLINE_RPC_TEXT "Selecting Character..." // Message at client startup | offline character #define STATE_RPC_TEXT "github.com/mehah/otclient" // State Text #define RPC_LARGE_IMAGE "rpc-logo" // Large Image Name (Imported to API) diff --git a/src/framework/core/adaptativeframecounter.h b/src/framework/core/adaptativeframecounter.h index 24856abca2..6685f3ff33 100644 --- a/src/framework/core/adaptativeframecounter.h +++ b/src/framework/core/adaptativeframecounter.h @@ -35,26 +35,26 @@ class AdaptativeFrameCounter void init() { m_timer.restart(); } bool update(); - uint16_t getFps() const { return m_fps; } - uint16_t getMaxFps() const { return m_maxFps; } - uint16_t getTargetFps() const { return m_targetFps; } + [[nodiscard]] uint16_t getFps() const { return m_fps; } + [[nodiscard]] uint16_t getMaxFps() const { return m_maxFps; } + [[nodiscard]] uint16_t getTargetFps() const { return m_targetFps; } void setMaxFps(const uint16_t max) { m_maxFps = max; } void setTargetFps(const uint16_t target) { if (m_targetFps != target) m_targetFps = target; } void resetTargetFps() { m_targetFps = 0; } - float getPercent() const { + [[nodiscard]] float getPercent() const { const float maxFps = std::clamp(m_targetFps, 1, std::max(m_maxFps, m_targetFps)); return ((maxFps - m_fps) / maxFps) * 100.f; } - float getFpsPercent(const float percent) const { + [[nodiscard]] float getFpsPercent(const float percent) const { return getFps() * (percent / 100); } private: - uint32_t getMaxPeriod(const uint16_t fps) const { return 1000000u / fps; } + [[nodiscard]] uint32_t getMaxPeriod(const uint16_t fps) const { return 1000000u / fps; } uint16_t m_maxFps{}; uint16_t m_targetFps{ 60u }; diff --git a/src/framework/core/application.h b/src/framework/core/application.h index e0ce3e79a5..34c25fe62d 100644 --- a/src/framework/core/application.h +++ b/src/framework/core/application.h @@ -56,7 +56,7 @@ class Application bool isRunning() { return m_running; } bool isStopping() { return m_stopping; } - bool isTerminated() const { return m_terminated; } + [[nodiscard]] bool isTerminated() const { return m_terminated; } const std::string& getName() { return m_appName; } const std::string& getCompactName() { return m_appCompactName; } const std::string& getOrganizationName() { return m_organizationName; } diff --git a/src/framework/core/binarytree.h b/src/framework/core/binarytree.h index 3dca246c6b..e0a636baef 100644 --- a/src/framework/core/binarytree.h +++ b/src/framework/core/binarytree.h @@ -38,7 +38,7 @@ class BinaryTree void seek(uint32_t pos); void skip(uint32_t len); - uint32_t tell() const { return m_pos; } + [[nodiscard]] uint32_t tell() const { return m_pos; } uint32_t size() { unserialize(); return m_buffer.size(); } uint8_t getU8(); diff --git a/src/framework/core/eventdispatcher.h b/src/framework/core/eventdispatcher.h index d984279535..6f041fc98f 100644 --- a/src/framework/core/eventdispatcher.h +++ b/src/framework/core/eventdispatcher.h @@ -45,19 +45,19 @@ enum class DispatcherType : uint8_t struct DispatcherContext { - bool isGroup(const TaskGroup _group) const { + [[nodiscard]] bool isGroup(const TaskGroup _group) const { return group == _group; } - bool isAsync() const { + [[nodiscard]] bool isAsync() const { return type == DispatcherType::AsyncEvent; } - auto getGroup() const { + [[nodiscard]] auto getGroup() const { return group; } - auto getType() const { + [[nodiscard]] auto getType() const { return type; } @@ -88,7 +88,7 @@ class EventDispatcher ScheduledEventPtr scheduleEvent(const std::function& callback, int delay); ScheduledEventPtr cycleEvent(const std::function& callback, int delay); - const auto& context() const { + [[nodiscard]] const auto& context() const { return dispacherContext; } @@ -122,7 +122,7 @@ class EventDispatcher inline void executeDeferEvents(); inline void executeScheduledEvents(); - const std::unique_ptr& getThreadTask() const { + [[nodiscard]] const std::unique_ptr& getThreadTask() const { return m_threads[stdext::getThreadId() % m_threads.size()]; } diff --git a/src/framework/core/graphicalapplication.h b/src/framework/core/graphicalapplication.h index b0b240a9cd..32ee0d4694 100644 --- a/src/framework/core/graphicalapplication.h +++ b/src/framework/core/graphicalapplication.h @@ -35,7 +35,7 @@ class ApplicationDrawEvents virtual void preLoad() = 0; virtual void draw(DrawPoolType type) = 0; - virtual bool canDraw(DrawPoolType type) const = 0; + [[nodiscard]] virtual bool canDraw(DrawPoolType type) const = 0; virtual bool isLoadingAsyncTexture() = 0; virtual bool isUsingProtobuf() = 0; virtual void onLoadingAsyncTextureChanged(bool loadingAsync) = 0; @@ -104,16 +104,16 @@ class GraphicalApplication final : public Application void setDrawTexts(const bool v) { m_drawText = v; } bool isDrawingTexts() { return m_drawText; } - float getHUDScale() const; + [[nodiscard]] float getHUDScale() const; void setHUDScale(float v); - float getCreatureInformationScale() const { return m_creatureInformationScale; } + [[nodiscard]] float getCreatureInformationScale() const { return m_creatureInformationScale; } void setCreatureInformationScale(const float v) { m_creatureInformationScale = v; } - float getAnimatedTextScale() const { return m_animatedTextScale; } + [[nodiscard]] float getAnimatedTextScale() const { return m_animatedTextScale; } void setAnimatedTextScale(const float v) { m_animatedTextScale = v; } - float getStaticTextScale() const { return m_staticTextScale; } + [[nodiscard]] float getStaticTextScale() const { return m_staticTextScale; } void setStaticTextScale(const float v) { m_staticTextScale = v; } bool isLoadingAsyncTexture(); diff --git a/src/framework/core/module.cpp b/src/framework/core/module.cpp index f1eb7f51d8..ecdd89c64a 100644 --- a/src/framework/core/module.cpp +++ b/src/framework/core/module.cpp @@ -86,8 +86,8 @@ bool Module::load() m_loaded = true; - g_logger.debug( "Loaded module '{}' ({:.2f}s)", m_name, (stdext::millis() - startTime) / 1000.0 -); + g_logger.debug("Loaded module '{}' ({:.2f}s)", m_name, (stdext::millis() - startTime) / 1000.0 + ); } catch (const stdext::exception& e) { // remove from package.loaded g_lua.getGlobalField("package", "loaded"); diff --git a/src/framework/core/modulemanager.cpp b/src/framework/core/modulemanager.cpp index 1965149afd..adcbebb5ac 100644 --- a/src/framework/core/modulemanager.cpp +++ b/src/framework/core/modulemanager.cpp @@ -175,7 +175,7 @@ void ModuleManager::enableAutoReload() { for (const auto& path : g_resources.listDirectoryFiles("/" + module->getName(), true, false, true)) { ticks_t time = g_resources.getFileTime(path); if (time > 0) { - data.files.emplace_back(std::make_shared(FileInfo{ path, time })); + data.files.emplace_back(std::make_shared(FileInfo{ .path = path, .time = time })); hasFile = true; } } diff --git a/src/framework/core/modulemanager.h b/src/framework/core/modulemanager.h index 6b8b986776..62a6195f3f 100644 --- a/src/framework/core/modulemanager.h +++ b/src/framework/core/modulemanager.h @@ -41,7 +41,7 @@ class ModuleManager std::deque getModules() { return m_modules; } ModulePtr getCurrentModule() { return m_currentModule; } void enableAutoReload(); - bool isAutoReloadEnabled() const { return m_reloadEnable; } + [[nodiscard]] bool isAutoReloadEnabled() const { return m_reloadEnable; } protected: void updateModuleLoadOrder(const ModulePtr& module); diff --git a/src/framework/core/resourcemanager.cpp b/src/framework/core/resourcemanager.cpp index 0297ba2b0b..cc069be201 100644 --- a/src/framework/core/resourcemanager.cpp +++ b/src/framework/core/resourcemanager.cpp @@ -789,4 +789,4 @@ std::unordered_map ResourceManager::decompressArchive( { std::unordered_map ret; return ret; -} +} \ No newline at end of file diff --git a/src/framework/core/resourcemanager.h b/src/framework/core/resourcemanager.h index 7fa1ac948f..70e6c7f6dc 100644 --- a/src/framework/core/resourcemanager.h +++ b/src/framework/core/resourcemanager.h @@ -57,8 +57,8 @@ class ResourceManager // String_view Support FileStreamPtr openFile(const std::string& fileName); - FileStreamPtr appendFile(const std::string& fileName) const; - FileStreamPtr createFile(const std::string& fileName) const; + [[nodiscard]] FileStreamPtr appendFile(const std::string& fileName) const; + [[nodiscard]] FileStreamPtr createFile(const std::string& fileName) const; bool deleteFile(const std::string& fileName); bool makeDir(const std::string& directory); diff --git a/src/framework/core/timer.h b/src/framework/core/timer.h index f13e5acd91..7231f3e715 100644 --- a/src/framework/core/timer.h +++ b/src/framework/core/timer.h @@ -33,11 +33,11 @@ class Timer void stop() { m_stopped = true; } void update(const ticks_t tick) { m_startTicks += tick; } - ticks_t startTicks() const { return m_startTicks; } - ticks_t ticksElapsed() const; - float timeElapsed() const { return ticksElapsed() / 1000.0f; } + [[nodiscard]] ticks_t startTicks() const { return m_startTicks; } + [[nodiscard]] ticks_t ticksElapsed() const; + [[nodiscard]] float timeElapsed() const { return ticksElapsed() / 1000.0f; } - bool running() const { return !m_stopped; } + [[nodiscard]] bool running() const { return !m_stopped; } private: ticks_t m_startTicks; diff --git a/src/framework/discord/discord.cpp b/src/framework/discord/discord.cpp index c29838658a..e38704da86 100644 --- a/src/framework/discord/discord.cpp +++ b/src/framework/discord/discord.cpp @@ -66,4 +66,4 @@ void Discord::update() g_dispatcher.scheduleEvent([this] { update(); }, 30000); } #endif -#endif +#endif \ No newline at end of file diff --git a/src/framework/graphics/animatedtexture.cpp b/src/framework/graphics/animatedtexture.cpp index c68d2bb7f5..ef5d12d337 100644 --- a/src/framework/graphics/animatedtexture.cpp +++ b/src/framework/graphics/animatedtexture.cpp @@ -26,8 +26,6 @@ #include #include -#include - AnimatedTexture::AnimatedTexture(const Size& size, const std::vector& frames, std::vector framesDelay, const uint16_t numPlays, bool buildMipmaps, bool compress) { if (!setupSize(size)) diff --git a/src/framework/graphics/animatedtexture.h b/src/framework/graphics/animatedtexture.h index 69dc9721d0..d3d87cc5bd 100644 --- a/src/framework/graphics/animatedtexture.h +++ b/src/framework/graphics/animatedtexture.h @@ -40,17 +40,17 @@ class AnimatedTexture final : public Texture void setSmooth(bool smooth) override; void setRepeat(bool repeat) override; - uint32_t getNumPlays() const { return m_numPlays; } + [[nodiscard]] uint32_t getNumPlays() const { return m_numPlays; } void setNumPlays(const uint32_t n) { m_numPlays = n; } - bool isOnMap() const { return m_onMap; } + [[nodiscard]] bool isOnMap() const { return m_onMap; } void setOnMap(const bool v) { m_onMap = v; } void update(); void restart() { m_animTimer.restart(); m_currentPlay = 0; m_currentFrame = 0; } - bool isAnimatedTexture() const override { return true; } - bool running() const { return m_animTimer.running(); } + [[nodiscard]] bool isAnimatedTexture() const override { return true; } + [[nodiscard]] bool running() const { return m_animTimer.running(); } void allowAtlasCache() override; diff --git a/src/framework/graphics/apngloader.cpp b/src/framework/graphics/apngloader.cpp index b07e8dea77..dd37c61e19 100644 --- a/src/framework/graphics/apngloader.cpp +++ b/src/framework/graphics/apngloader.cpp @@ -41,14 +41,23 @@ #define swap32(data) ((swap16(data) << 16) | swap16(data >> 16)) #endif -#define PNG_ZBUF_SIZE 32768 +enum +{ + PNG_ZBUF_SIZE = 32768 +}; -#define PNG_DISPOSE_OP_NONE 0x00 -#define PNG_DISPOSE_OP_BACKGROUND 0x01 -#define PNG_DISPOSE_OP_PREVIOUS 0x02 +enum +{ + PNG_DISPOSE_OP_NONE = 0x00, + PNG_DISPOSE_OP_BACKGROUND = 0x01, + PNG_DISPOSE_OP_PREVIOUS = 0x02 +}; -#define PNG_BLEND_OP_SOURCE 0x00 -#define PNG_BLEND_OP_OVER 0x01 +enum +{ + PNG_BLEND_OP_SOURCE = 0x00, + PNG_BLEND_OP_OVER = 0x01 +}; #define notabc(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97)) diff --git a/src/framework/graphics/bitmapfont.cpp b/src/framework/graphics/bitmapfont.cpp index 0e8558b066..3a1952ac02 100644 --- a/src/framework/graphics/bitmapfont.cpp +++ b/src/framework/graphics/bitmapfont.cpp @@ -27,6 +27,7 @@ #include "textureatlas.h" #include + #include "drawpoolmanager.h" static thread_local std::vector s_glyphsPositions(1); @@ -302,9 +303,9 @@ void BitmapFont::calculateGlyphsPositions(std::string_view text, return; } - if (static_cast(glyphsPositions.size()) < textLength) + if (std::cmp_less(glyphsPositions.size(), textLength)) glyphsPositions.resize(textLength); - if (static_cast(glyphsPositions.capacity()) < textLength) + if (std::cmp_less(glyphsPositions.capacity(), textLength)) glyphsPositions.reserve(std::max(1024, textLength)); const unsigned char* p = reinterpret_cast(text.data()); diff --git a/src/framework/graphics/bitmapfont.h b/src/framework/graphics/bitmapfont.h index 9fbc3a5604..3b8dc5a568 100644 --- a/src/framework/graphics/bitmapfont.h +++ b/src/framework/graphics/bitmapfont.h @@ -35,11 +35,11 @@ class BitmapFont void drawText(std::string_view text, const Point& startPos, const Color& color = Color::white); void drawText(std::string_view text, const Rect& screenCoords, const Color& color = Color::white, Fw::AlignmentFlag align = Fw::AlignTopLeft); - std::vector> getDrawTextCoords(std::string_view text, - const Size& textBoxSize, - Fw::AlignmentFlag align, - const Rect& screenCoords, - const std::vector& glyphsPositions) const noexcept; + [[nodiscard]] std::vector> getDrawTextCoords(std::string_view text, + const Size& textBoxSize, + Fw::AlignmentFlag align, + const Rect& screenCoords, + const std::vector& glyphsPositions) const noexcept; void fillTextCoords(const CoordsBufferPtr& coords, std::string_view text, const Size& textBoxSize, Fw::AlignmentFlag align, @@ -59,14 +59,14 @@ class BitmapFont std::string wrapText(std::string_view text, int maxWidth, std::vector>* colors = nullptr) noexcept; - inline const std::string& getName() const noexcept { return m_name; } - inline int getGlyphHeight() const noexcept { return m_glyphHeight; } + [[nodiscard]] inline const std::string& getName() const noexcept { return m_name; } + [[nodiscard]] inline int getGlyphHeight() const noexcept { return m_glyphHeight; } inline const Rect* getGlyphsTextureCoords() noexcept { return m_glyphsTextureCoords; } inline const Size* getGlyphsSize() noexcept { return m_glyphsSize; } - inline const TexturePtr& getTexture() const noexcept { return m_texture; } - inline int getYOffset() const noexcept { return m_yOffset; } - inline Size getGlyphSpacing() const noexcept { return m_glyphSpacing; } - const AtlasRegion* getAtlasRegion() const noexcept; + [[nodiscard]] inline const TexturePtr& getTexture() const noexcept { return m_texture; } + [[nodiscard]] inline int getYOffset() const noexcept { return m_yOffset; } + [[nodiscard]] inline Size getGlyphSpacing() const noexcept { return m_glyphSpacing; } + [[nodiscard]] const AtlasRegion* getAtlasRegion() const noexcept; private: void calculateGlyphsWidthsAutomatically(const ImagePtr& image, const Size& glyphSize); diff --git a/src/framework/graphics/cachedtext.h b/src/framework/graphics/cachedtext.h index 0268621d51..c97bb732f3 100644 --- a/src/framework/graphics/cachedtext.h +++ b/src/framework/graphics/cachedtext.h @@ -36,11 +36,11 @@ class CachedText void setText(std::string_view text); void setAlign(Fw::AlignmentFlag align); - Size getTextSize() const { return m_textSize; } - std::string getText() const { return m_text; } - bool hasText() const { return !m_text.empty(); } - BitmapFontPtr getFont() const { return m_font; } - Fw::AlignmentFlag getAlign() const { return m_align; } + [[nodiscard]] Size getTextSize() const { return m_textSize; } + [[nodiscard]] std::string getText() const { return m_text; } + [[nodiscard]] bool hasText() const { return !m_text.empty(); } + [[nodiscard]] BitmapFontPtr getFont() const { return m_font; } + [[nodiscard]] Fw::AlignmentFlag getAlign() const { return m_align; } private: void update(); diff --git a/src/framework/graphics/coordsbuffer.h b/src/framework/graphics/coordsbuffer.h index 0f83899376..1a85121364 100644 --- a/src/framework/graphics/coordsbuffer.h +++ b/src/framework/graphics/coordsbuffer.h @@ -83,12 +83,12 @@ class CoordsBuffer m_textureCoordArray.append(&buffer->m_textureCoordArray); } - const float* getVertexArray() const { return m_vertexArray.vertices(); } - const float* getTextureCoordArray() const { return m_textureCoordArray.vertices(); } - int getVertexCount() const { return m_vertexArray.vertexCount(); } - int getTextureCoordCount() const { return m_textureCoordArray.vertexCount(); } + [[nodiscard]] const float* getVertexArray() const { return m_vertexArray.vertices(); } + [[nodiscard]] const float* getTextureCoordArray() const { return m_textureCoordArray.vertices(); } + [[nodiscard]] int getVertexCount() const { return m_vertexArray.vertexCount(); } + [[nodiscard]] int getTextureCoordCount() const { return m_textureCoordArray.vertexCount(); } - size_t size() const { + [[nodiscard]] size_t size() const { return std::max(m_vertexArray.size(), m_textureCoordArray.size()); } diff --git a/src/framework/graphics/drawpool.cpp b/src/framework/graphics/drawpool.cpp index 847eed7c76..56a5ca3438 100644 --- a/src/framework/graphics/drawpool.cpp +++ b/src/framework/graphics/drawpool.cpp @@ -397,12 +397,14 @@ std::shared_ptr DrawPool::getCoordsBuffer() { } else coordsBuffer = new CoordsBuffer(); - return std::shared_ptr(coordsBuffer, [this](CoordsBuffer* ptr) { + return { + coordsBuffer, [this](CoordsBuffer* ptr) { if (m_enabled) { ptr->clear(); m_coordsCache.emplace_back(ptr); } else { delete ptr; } - }); + } + }; } \ No newline at end of file diff --git a/src/framework/graphics/drawpool.h b/src/framework/graphics/drawpool.h index 176769a0e5..2d5e0ffe96 100644 --- a/src/framework/graphics/drawpool.h +++ b/src/framework/graphics/drawpool.h @@ -22,8 +22,6 @@ #pragma once -#include - #include "declarations.h" #include "framebuffer.h" #include "framework/core/timer.h" @@ -68,7 +66,7 @@ struct DrawHashController return false; } - bool isLast(const size_t hash) const { + [[nodiscard]] bool isLast(const size_t hash) const { return m_lastObjectHash == hash; } @@ -76,7 +74,7 @@ struct DrawHashController m_currentHash = 1; } - bool wasModified() const { + [[nodiscard]] bool wasModified() const { return m_currentHash != m_lastHash; } diff --git a/src/framework/graphics/drawpoolmanager.h b/src/framework/graphics/drawpoolmanager.h index a39e534009..335dd8a51c 100644 --- a/src/framework/graphics/drawpoolmanager.h +++ b/src/framework/graphics/drawpoolmanager.h @@ -29,7 +29,7 @@ class DrawPoolManager { public: - DrawPool* get(const DrawPoolType type) const { return m_pools[static_cast(type)]; } + [[nodiscard]] DrawPool* get(const DrawPoolType type) const { return m_pools[static_cast(type)]; } void select(DrawPoolType type); void preDraw(const DrawPoolType type, const std::function& f, const bool alwaysDraw = false) { preDraw(type, f, nullptr, {}, {}, Color::alpha, alwaysDraw); } @@ -63,12 +63,12 @@ class DrawPoolManager void setCompositionMode(const CompositionMode mode, const bool onlyOnce = false) const { getCurrentPool()->setCompositionMode(mode, onlyOnce); } void setDrawOrder(DrawOrder order)const { getCurrentPool()->setDrawOrder(order); } - bool shaderNeedFramebuffer() const { return getCurrentPool()->getCurrentState().shaderProgram && getCurrentPool()->getCurrentState().shaderProgram->useFramebuffer(); } + [[nodiscard]] bool shaderNeedFramebuffer() const { return getCurrentPool()->getCurrentState().shaderProgram && getCurrentPool()->getCurrentState().shaderProgram->useFramebuffer(); } void setShaderProgram(const PainterShaderProgramPtr& shaderProgram, const std::function& action) const { getCurrentPool()->setShaderProgram(shaderProgram, false, action); } void setShaderProgram(const PainterShaderProgramPtr& shaderProgram, const bool onlyOnce = false, const std::function& action = nullptr) const { getCurrentPool()->setShaderProgram(shaderProgram, onlyOnce, action); } - float getOpacity() const { return getCurrentPool()->getOpacity(); } - Rect getClipRect() const { return getCurrentPool()->getClipRect(); } + [[nodiscard]] float getOpacity() const { return getCurrentPool()->getOpacity(); } + [[nodiscard]] Rect getClipRect() const { return getCurrentPool()->getClipRect(); } void resetState() const { getCurrentPool()->resetState(); } void resetOpacity() const { getCurrentPool()->resetOpacity(); } @@ -87,12 +87,12 @@ class DrawPoolManager void rotate(const Point& p, const float angle) const { getCurrentPool()->rotate(p, angle); } void setScaleFactor(const float scale) const { getCurrentPool()->setScaleFactor(scale); } - float getScaleFactor() const { return getCurrentPool()->getScaleFactor(); } - bool isScaled() const { return getCurrentPool()->isScaled(); } - uint16_t getScaledSpriteSize() const { return m_spriteSize * getScaleFactor(); } - const auto getAtlas() const { return getCurrentPool()->getAtlas(); } - bool isValid() const; - auto getDrawOrder() const { return getCurrentPool()->getDrawOrder(); } + [[nodiscard]] float getScaleFactor() const { return getCurrentPool()->getScaleFactor(); } + [[nodiscard]] bool isScaled() const { return getCurrentPool()->isScaled(); } + [[nodiscard]] uint16_t getScaledSpriteSize() const { return m_spriteSize * getScaleFactor(); } + [[nodiscard]] const auto getAtlas() const { return getCurrentPool()->getAtlas(); } + [[nodiscard]] bool isValid() const; + [[nodiscard]] auto getDrawOrder() const { return getCurrentPool()->getDrawOrder(); } template void setParameter(std::string_view name, T&& value) { getCurrentPool()->setParameter(name, value); } @@ -104,18 +104,18 @@ class DrawPoolManager void flush() const { if (getCurrentPool()) getCurrentPool()->flush(); } - DrawPoolType getCurrentType() const; + [[nodiscard]] DrawPoolType getCurrentType() const; void repaint(const DrawPoolType drawPool) const { get(drawPool)->repaint(); } - bool isPreDrawing() const; + [[nodiscard]] bool isPreDrawing() const; void removeTextureFromAtlas(uint32_t id, bool smooth); private: - DrawPool* getCurrentPool() const; + [[nodiscard]] DrawPool* getCurrentPool() const; void draw(); void init(uint16_t spriteSize); diff --git a/src/framework/graphics/fontmanager.h b/src/framework/graphics/fontmanager.h index 00c506df50..c16ae5661b 100644 --- a/src/framework/graphics/fontmanager.h +++ b/src/framework/graphics/fontmanager.h @@ -36,8 +36,8 @@ class FontManager bool fontExists(std::string_view fontName); BitmapFontPtr getFont(std::string_view fontName); - BitmapFontPtr getDefaultFont() const { return m_defaultFont; } - BitmapFontPtr getDefaultWidgetFont() const { return m_defaultWidgetFont; } + [[nodiscard]] BitmapFontPtr getDefaultFont() const { return m_defaultFont; } + [[nodiscard]] BitmapFontPtr getDefaultWidgetFont() const { return m_defaultWidgetFont; } void setDefaultFont(const BitmapFontPtr& font) { m_defaultFont = font; } void setDefaultWidgetFont(const BitmapFontPtr& font) { m_defaultWidgetFont = font; } diff --git a/src/framework/graphics/framebuffer.h b/src/framework/graphics/framebuffer.h index 6b00c9d7aa..9f935ff3ef 100644 --- a/src/framework/graphics/framebuffer.h +++ b/src/framework/graphics/framebuffer.h @@ -41,17 +41,17 @@ class FrameBuffer void setSmooth(const bool enabled) { m_smooth = enabled; m_texture = nullptr; } bool resize(const Size& size); - bool isValid() const { return m_texture != nullptr; } - bool canDraw() const; - bool isAutoClear() const { return m_autoClear; } + [[nodiscard]] bool isValid() const { return m_texture != nullptr; } + [[nodiscard]] bool canDraw() const; + [[nodiscard]] bool isAutoClear() const { return m_autoClear; } void setAutoClear(bool v) { m_autoClear = v; } void setAlphaWriting(bool v) { m_useAlphaWriting = v; } void setAutoResetState(bool v) { m_isScene = v; } - TexturePtr getTexture() const { return m_texture; } + [[nodiscard]] TexturePtr getTexture() const { return m_texture; } TexturePtr extractTexture(); - Size getSize() const { return m_texture->getSize(); } + [[nodiscard]] Size getSize() const { return m_texture->getSize(); } void setCompositionMode(const CompositionMode mode) { m_compositeMode = mode; } void disableBlend() { m_disableBlend = true; } diff --git a/src/framework/graphics/graphics.h b/src/framework/graphics/graphics.h index 59e533eb08..c0ecd1013c 100644 --- a/src/framework/graphics/graphics.h +++ b/src/framework/graphics/graphics.h @@ -35,7 +35,7 @@ class Graphics void resize(const Size& size); - int getMaxTextureSize() const { return m_maxTextureSize; } + [[nodiscard]] int getMaxTextureSize() const { return m_maxTextureSize; } const Size& getViewportSize() { return m_viewportSize; } std::string getVendor() { return m_vendor; } @@ -43,7 +43,7 @@ class Graphics std::string getVersion() { return m_version; } std::string getExtensions() { return m_extensions; } - bool ok() const { return m_ok; } + [[nodiscard]] bool ok() const { return m_ok; } private: bool m_ok{ false }; diff --git a/src/framework/graphics/image.h b/src/framework/graphics/image.h index 091ac1444b..3b5bf3eae3 100644 --- a/src/framework/graphics/image.h +++ b/src/framework/graphics/image.h @@ -63,14 +63,14 @@ class Image std::vector& getPixels() { return m_pixels; } uint8_t* getPixelData() { return &m_pixels[0]; } - int getPixelCount() const { return m_size.area(); } - const Size& getSize() const { return m_size; } - int getWidth() const { return m_size.width(); } - int getHeight() const { return m_size.height(); } - int getBpp() const { return m_bpp; } + [[nodiscard]] int getPixelCount() const { return m_size.area(); } + [[nodiscard]] const Size& getSize() const { return m_size; } + [[nodiscard]] int getWidth() const { return m_size.width(); } + [[nodiscard]] int getHeight() const { return m_size.height(); } + [[nodiscard]] int getBpp() const { return m_bpp; } uint8_t* getPixel(const int x, const int y) { return &m_pixels[static_cast(y * m_size.width() + x) * m_bpp]; } - bool hasTransparentPixel() const { return m_transparentPixel; } + [[nodiscard]] bool hasTransparentPixel() const { return m_transparentPixel; } void setTransparentPixel(const bool value) { m_transparentPixel = value; } private: diff --git a/src/framework/graphics/painter.h b/src/framework/graphics/painter.h index 91e81b7c7b..eff9ad737a 100644 --- a/src/framework/graphics/painter.h +++ b/src/framework/graphics/painter.h @@ -63,21 +63,21 @@ class Painter void drawCoords(const CoordsBuffer& coordsBuffer, DrawMode drawMode = DrawMode::TRIANGLES); void drawLine(const std::vector& vertex, int size, int width) const; - float getOpacity() const { return m_opacity; } - bool getAlphaWriting() const { return m_alphaWriting; } - - const auto& getTextureMatrix() const { return m_textureMatrix; } - Matrix3 getTransformMatrix(const Size& size) const; - Matrix3 getTransformMatrix() const { return m_transformMatrix; } - Matrix3 getProjectionMatrix() const { return m_projectionMatrix; } - - Color getColor() const { return m_color; } - Rect getClipRect() const { return m_clipRect; } - Size getResolution() const { return m_resolution; } - BlendEquation getBlendEquation() const { return m_blendEquation; } - CompositionMode getCompositionMode() const { return m_compositionMode; } - PainterShaderProgram* getShaderProgram() const { return m_shaderProgram; } - PainterShaderProgramPtr getReplaceColorShader() const { return m_drawReplaceColorProgram; } + [[nodiscard]] float getOpacity() const { return m_opacity; } + [[nodiscard]] bool getAlphaWriting() const { return m_alphaWriting; } + + [[nodiscard]] const auto& getTextureMatrix() const { return m_textureMatrix; } + [[nodiscard]] Matrix3 getTransformMatrix(const Size& size) const; + [[nodiscard]] Matrix3 getTransformMatrix() const { return m_transformMatrix; } + [[nodiscard]] Matrix3 getProjectionMatrix() const { return m_projectionMatrix; } + + [[nodiscard]] Color getColor() const { return m_color; } + [[nodiscard]] Rect getClipRect() const { return m_clipRect; } + [[nodiscard]] Size getResolution() const { return m_resolution; } + [[nodiscard]] BlendEquation getBlendEquation() const { return m_blendEquation; } + [[nodiscard]] CompositionMode getCompositionMode() const { return m_compositionMode; } + [[nodiscard]] PainterShaderProgram* getShaderProgram() const { return m_shaderProgram; } + [[nodiscard]] PainterShaderProgramPtr getReplaceColorShader() const { return m_drawReplaceColorProgram; } void setColor(const Color& color) { if (m_color != color) m_color = color; } void setTexture(const TexturePtr&); diff --git a/src/framework/graphics/particle.h b/src/framework/graphics/particle.h index c21fa8477a..33f8d14327 100644 --- a/src/framework/graphics/particle.h +++ b/src/framework/graphics/particle.h @@ -43,7 +43,7 @@ class Particle void render() const; void update(float elapsedTime); - bool hasFinished() const { return m_finished; } + [[nodiscard]] bool hasFinished() const { return m_finished; } PointF getPosition() { return m_position; } PointF getVelocity() { return m_velocity; } diff --git a/src/framework/graphics/particleaffector.h b/src/framework/graphics/particleaffector.h index d5bc34d251..800996c044 100644 --- a/src/framework/graphics/particleaffector.h +++ b/src/framework/graphics/particleaffector.h @@ -34,7 +34,7 @@ class ParticleAffector virtual void load(const OTMLNodePtr& node); virtual void updateParticle(const ParticlePtr&, float) const = 0; - bool hasFinished() const { return m_finished; } + [[nodiscard]] bool hasFinished() const { return m_finished; } protected: bool m_finished{ false }; diff --git a/src/framework/graphics/particleeffect.h b/src/framework/graphics/particleeffect.h index 49a47a444f..567a2dc086 100644 --- a/src/framework/graphics/particleeffect.h +++ b/src/framework/graphics/particleeffect.h @@ -47,7 +47,7 @@ class ParticleEffect ParticleEffect() = default; void load(const ParticleEffectTypePtr& effectType); - bool hasFinished() const { return m_systems.empty(); } + [[nodiscard]] bool hasFinished() const { return m_systems.empty(); } void render() const; void update(); diff --git a/src/framework/graphics/particleemitter.h b/src/framework/graphics/particleemitter.h index 81b5cdc4ca..cf5c99e3d1 100644 --- a/src/framework/graphics/particleemitter.h +++ b/src/framework/graphics/particleemitter.h @@ -34,7 +34,7 @@ class ParticleEmitter void update(float elapsedTime, const ParticleSystemPtr& system); - bool hasFinished() const { return m_finished; } + [[nodiscard]] bool hasFinished() const { return m_finished; } private: // self related diff --git a/src/framework/graphics/particlemanager.h b/src/framework/graphics/particlemanager.h index d440eda952..923b3805a4 100644 --- a/src/framework/graphics/particlemanager.h +++ b/src/framework/graphics/particlemanager.h @@ -39,7 +39,7 @@ class ParticleManager ParticleTypePtr getParticleType(const std::string& name) { return m_particleTypes[name]; } ParticleEffectTypePtr getParticleEffectType(const std::string& name) { return m_effectsTypes[name]; } - const stdext::map& getParticleTypes() const { return m_particleTypes; } + [[nodiscard]] const stdext::map& getParticleTypes() const { return m_particleTypes; } const stdext::map& getEffectsTypes() { return m_effectsTypes; } private: diff --git a/src/framework/graphics/particletype.h b/src/framework/graphics/particletype.h index a5694db9e0..cecd87b9cb 100644 --- a/src/framework/graphics/particletype.h +++ b/src/framework/graphics/particletype.h @@ -31,7 +31,7 @@ class ParticleType { public: void load(const OTMLNodePtr& node); - std::string getName() const { return pName; } + [[nodiscard]] std::string getName() const { return pName; } protected: diff --git a/src/framework/graphics/shader.h b/src/framework/graphics/shader.h index 1c843eabfd..f5a48a197e 100644 --- a/src/framework/graphics/shader.h +++ b/src/framework/graphics/shader.h @@ -37,12 +37,12 @@ class Shader Shader(ShaderType shaderType); ~Shader(); - bool compileSourceCode(std::string_view sourceCode) const; - bool compileSourceFile(std::string_view sourceFile) const; - std::string log() const; + [[nodiscard]] bool compileSourceCode(std::string_view sourceCode) const; + [[nodiscard]] bool compileSourceFile(std::string_view sourceFile) const; + [[nodiscard]] std::string log() const; - uint32_t getShaderId() const { return m_shaderId; } - ShaderType getShaderType() const { return m_shaderType; } + [[nodiscard]] uint32_t getShaderId() const { return m_shaderId; } + [[nodiscard]] ShaderType getShaderType() const { return m_shaderType; } private: uint32_t m_shaderId{ 0 }; diff --git a/src/framework/graphics/shadermanager.h b/src/framework/graphics/shadermanager.h index 85fc12899f..2cabf44991 100644 --- a/src/framework/graphics/shadermanager.h +++ b/src/framework/graphics/shadermanager.h @@ -58,7 +58,8 @@ class ShaderManager void addMultiTexture(std::string_view name, std::string_view file); PainterShaderProgramPtr getShader(std::string_view name); - PainterShaderProgramPtr getShaderById(const uint8_t id) const { + + [[nodiscard]] PainterShaderProgramPtr getShaderById(const uint8_t id) const { return id > 0 && id <= m_shadersVector.size() ? m_shadersVector[id - 1] : nullptr; } diff --git a/src/framework/graphics/texture.h b/src/framework/graphics/texture.h index 22aa2349bf..9ac0db9267 100644 --- a/src/framework/graphics/texture.h +++ b/src/framework/graphics/texture.h @@ -45,26 +45,26 @@ class Texture void setUpsideDown(bool upsideDown); void setTime(const ticks_t time) { m_time = time; } - const Size& getSize() const { return m_size; } - auto getTransformMatrixId() const { return m_transformMatrixId; } - - const auto getAtlasRegion(Fw::TextureAtlasType type) const { return m_atlas[type]; } - const AtlasRegion* getAtlasRegion() const; - - ticks_t getTime() const { return m_time; } - uint32_t getId() const { return m_id; } - uint32_t getUniqueId() const { return m_uniqueId; } - size_t hash() const { return m_hash; } - - int getWidth() const { return m_size.width(); } - int getHeight() const { return m_size.height(); } - - virtual bool isAnimatedTexture() const { return false; } - bool isEmpty() const { return m_id == 0; } - bool hasRepeat() const { return getProp(repeat); } - bool hasMipmaps() const { return getProp(hasMipMaps); } - bool isSmooth() const { return getProp(smooth); } - bool canCacheInAtlas() const { return getProp(Prop::_allowAtlasCache); } + [[nodiscard]] const Size& getSize() const { return m_size; } + [[nodiscard]] auto getTransformMatrixId() const { return m_transformMatrixId; } + + [[nodiscard]] const auto getAtlasRegion(Fw::TextureAtlasType type) const { return m_atlas[type]; } + [[nodiscard]] const AtlasRegion* getAtlasRegion() const; + + [[nodiscard]] ticks_t getTime() const { return m_time; } + [[nodiscard]] uint32_t getId() const { return m_id; } + [[nodiscard]] uint32_t getUniqueId() const { return m_uniqueId; } + [[nodiscard]] size_t hash() const { return m_hash; } + + [[nodiscard]] int getWidth() const { return m_size.width(); } + [[nodiscard]] int getHeight() const { return m_size.height(); } + + [[nodiscard]] virtual bool isAnimatedTexture() const { return false; } + [[nodiscard]] bool isEmpty() const { return m_id == 0; } + [[nodiscard]] bool hasRepeat() const { return getProp(repeat); } + [[nodiscard]] bool hasMipmaps() const { return getProp(hasMipMaps); } + [[nodiscard]] bool isSmooth() const { return getProp(smooth); } + [[nodiscard]] bool canCacheInAtlas() const { return getProp(Prop::_allowAtlasCache); } bool setupSize(const Size& size); virtual void allowAtlasCache(); @@ -106,7 +106,7 @@ class Texture uint16_t m_props{ 0 }; void setProp(const Prop prop, const bool v) { if (v) m_props |= prop; else m_props &= ~prop; } - bool getProp(const Prop prop) const { return m_props & prop; }; + [[nodiscard]] bool getProp(const Prop prop) const { return m_props & prop; }; friend class GarbageCollection; friend class TextureManager; diff --git a/src/framework/graphics/textureatlas.cpp b/src/framework/graphics/textureatlas.cpp index a6e0cf3aae..e4812b174f 100644 --- a/src/framework/graphics/textureatlas.cpp +++ b/src/framework/graphics/textureatlas.cpp @@ -93,7 +93,7 @@ void TextureAtlas::createNewLayer(bool smooth) { fbo->setSmooth(smooth); fbo->resize(m_size); - FreeRegion newRegion = { 0, 0, m_size.width(), m_size.height(), static_cast(m_filterGroups[smooth].layers.size()) }; + FreeRegion newRegion = { .x = 0, .y = 0, .width = m_size.width(), .height = m_size.height(), .layer = static_cast(m_filterGroups[smooth].layers.size()) }; m_filterGroups[smooth].layers.emplace_back(std::move(fbo)); m_filterGroups[smooth].freeRegions.insert(newRegion); diff --git a/src/framework/graphics/textureatlas.h b/src/framework/graphics/textureatlas.h index 241bce6af3..420cc4039d 100644 --- a/src/framework/graphics/textureatlas.h +++ b/src/framework/graphics/textureatlas.h @@ -48,7 +48,7 @@ struct FreeRegion return (y != other.y) ? (y < other.y) : (x < other.x); } - bool canFit(int texWidth, int texHeight) const { + [[nodiscard]] bool canFit(int texWidth, int texHeight) const { return width >= texWidth && height >= texHeight; } }; @@ -78,11 +78,11 @@ class TextureAtlas void addTexture(const TexturePtr& texture); void removeTexture(uint32_t id, bool smooth); - Size getSize() const { return m_size; } + [[nodiscard]] Size getSize() const { return m_size; } void flush(); - auto getType() const { return m_type; } + [[nodiscard]] auto getType() const { return m_type; } private: struct Layer @@ -111,7 +111,7 @@ class TextureAtlas auto insertRegion = [&](int x, int y, int w, int h) { if (w > 0 && h > 0) { - FreeRegion r = { x, y, w, h, region.layer }; + FreeRegion r = { .x = x, .y = y, .width = w, .height = h, .layer = region.layer }; m_filterGroups[smooth].freeRegions.insert(r); m_filterGroups[smooth].freeRegionsBySize[w * h].insert(r); } diff --git a/src/framework/graphics/texturemanager.cpp b/src/framework/graphics/texturemanager.cpp index c254d63d2a..b5f62f4303 100644 --- a/src/framework/graphics/texturemanager.cpp +++ b/src/framework/graphics/texturemanager.cpp @@ -112,7 +112,7 @@ TexturePtr TextureManager::getTexture(const std::string& fileName, const bool sm #ifdef FRAMEWORK_NET // load texture from "virtual directory" - if (filePath.substr(0, 11) == "/downloads/") { + if (filePath.starts_with("/downloads/")) { std::string _filePath = filePath; const auto& fileDownload = g_http.getFile(_filePath.erase(0, 11)); if (fileDownload) { diff --git a/src/framework/graphics/vertexarray.h b/src/framework/graphics/vertexarray.h index 95bdbf9d7c..77c3f31238 100644 --- a/src/framework/graphics/vertexarray.h +++ b/src/framework/graphics/vertexarray.h @@ -147,9 +147,9 @@ class VertexArray void clear() { m_buffer.clear(); } - const float* vertices() const { return m_buffer.data(); } - int vertexCount() const { return m_buffer.size() / 2; } - int size() const { return m_buffer.size(); } + [[nodiscard]] const float* vertices() const { return m_buffer.data(); } + [[nodiscard]] int vertexCount() const { return m_buffer.size() / 2; } + [[nodiscard]] int size() const { return m_buffer.size(); } private: std::vector m_buffer; diff --git a/src/framework/html/cssparser.cpp b/src/framework/html/cssparser.cpp index 8e79c362a6..06e0ae8514 100644 --- a/src/framework/html/cssparser.cpp +++ b/src/framework/html/cssparser.cpp @@ -34,10 +34,10 @@ namespace css { }; static inline bool isNthLike(const std::string& name) { - return name.rfind("nth-child", 0) == 0 - || name.rfind("nth-last-child", 0) == 0 - || name.rfind("nth-of-type", 0) == 0 - || name.rfind("nth-last-of-type", 0) == 0; + return name.starts_with("nth-child") + || name.starts_with("nth-last-child") + || name.starts_with("nth-of-type") + || name.starts_with("nth-last-of-type"); } static inline bool isStructuralPseudo(const std::string& name) { @@ -81,10 +81,10 @@ namespace css { }; auto isNthLike = [](const std::string& name) { - return name.rfind("nth-child", 0) == 0 - || name.rfind("nth-last-child", 0) == 0 - || name.rfind("nth-of-type", 0) == 0 - || name.rfind("nth-last-of-type", 0) == 0; + return name.starts_with("nth-child") + || name.starts_with("nth-last-child") + || name.starts_with("nth-of-type") + || name.starts_with("nth-last-of-type"); }; for (size_t i = 0; i < sel.size();) { @@ -142,11 +142,11 @@ namespace css { for (const auto& part : parts) collect_pseudos(part, outPseudos, negated); } else { if (kEventPseudos.count(name)) - outPseudos.push_back({ name, negated }); + outPseudos.push_back({ .name = name, .negated = negated }); } } else { if (kEventPseudos.count(name)) - outPseudos.push_back({ name, negated }); + outPseudos.push_back({ .name = name, .negated = negated }); } } continue; @@ -199,8 +199,8 @@ namespace css { auto parts = split_selector_list(inside); std::string out; bool any = false; - for (size_t k = 0; k < parts.size(); ++k) { - std::string p = strip_pseudos_for_filter(parts[k]); + for (const auto& part : parts) { + std::string p = strip_pseudos_for_filter(part); detail::trim_inplace(p); if (p == "*") p.clear(); if (!p.empty()) { @@ -219,10 +219,10 @@ namespace css { }; auto isNthLike = [](const std::string& name) { - return name.rfind("nth-child", 0) == 0 - || name.rfind("nth-last-child", 0) == 0 - || name.rfind("nth-of-type", 0) == 0 - || name.rfind("nth-last-of-type", 0) == 0; + return name.starts_with("nth-child") + || name.starts_with("nth-last-child") + || name.starts_with("nth-of-type") + || name.starts_with("nth-last-of-type"); }; auto isStructural = [&](const std::string& name) { if (isNthLike(name)) return true; @@ -373,7 +373,7 @@ namespace css { else if (c == '}') { if (--depth == 0) { ++i; break; } } } std::string inner = s.substr(blockStart, (i - blockStart - 1)); - items.push_back({ "", inner, true, prelude }); + items.push_back({ .selectors = "", .block = inner, .is_at_media = true, .at_prelude = prelude }); continue; } size_t selStart = i; @@ -391,7 +391,7 @@ namespace css { else if (c == '}') { if (--depth == 0) { ++i; break; } } } std::string block = s.substr(blockStart, (i - blockStart - 1)); - items.push_back({ selectors, block, false, {} }); + items.push_back({ .selectors = selectors, .block = block, .is_at_media = false, .at_prelude = {} }); } return items; } @@ -443,7 +443,7 @@ namespace css { if (prop.starts_with("--")) prop.erase(0, 2); - out.push_back({ prop, val, important }); + out.push_back({ .property = prop, .value = val, .important = important }); } if (i < N && s[i] == ';') ++i; } diff --git a/src/framework/html/htmlmanager.cpp b/src/framework/html/htmlmanager.cpp index cf82b815b7..da950f86fe 100644 --- a/src/framework/html/htmlmanager.cpp +++ b/src/framework/html/htmlmanager.cpp @@ -118,7 +118,7 @@ namespace { auto& styleMap = child->getStyles()[style]; auto it = styleMap.find(prop); if (it == styleMap.end() || !it->second.important) { - child->getStyles()[style][prop] = { value , std::string{htmlId} }; + child->getStyles()[style][prop] = { .value = value , .inheritedFromId = std::string{htmlId} }; setChildrenStyles(htmlId, child.get(), style, prop, value); } } @@ -231,7 +231,8 @@ namespace { auto& styleMap = node->getStyles()[style]; auto it = styleMap.find(decl.property); if (it == styleMap.end() || !it->second.important) { - styleMap[decl.property] = { decl.value , "", decl.important }; + styleMap[decl.property] = { .value = decl.value , .inheritedFromId = "", + .important = decl.important }; if (!is_all && isInheritable(decl.property)) { setChildrenStyles(widget->getHtmlId(), node.get(), style, decl.property, decl.value); } @@ -248,7 +249,7 @@ namespace { auto& styleMap = node->getStyles()["styles"]; auto it = styleMap.find(decl.property); if (it == styleMap.end() || !it->second.important) { - styleMap[decl.property] = { decl.value , "", decl.important }; + styleMap[decl.property] = { .value = decl.value , .inheritedFromId = "", .important = decl.important }; if (!is_all && isInheritable(decl.property)) { setChildrenStyles(widget->getHtmlId(), node.get(), "styles", decl.property, decl.value); } @@ -354,7 +355,7 @@ void applyAttributesAndStyles(UIWidget* widget, HtmlNode* node, std::unordered_m } for (const auto& [prop, value] : node->getAttrStyles()) { - stylesMerge[prop] = { value , "", false }; + stylesMerge[prop] = { .value = value , .inheritedFromId = "", .important = false }; } for (const auto [prop, value] : stylesMerge) { @@ -448,7 +449,7 @@ UIWidgetPtr HtmlManager::readNode(DataRoot& root, const UIWidgetPtr& parent, con n->getInheritableStyles() = parent->getHtmlNode()->getInheritableStyles(); for (const auto& [styleName, styleMap] : n->getInheritableStyles()) { for (auto& [style, value] : styleMap) - n->getStyles()[styleName][style] = { value , parent->getHtmlId() }; + n->getStyles()[styleName][style] = { .value = value , .inheritedFromId = parent->getHtmlId() }; } } widget = createWidgetFromNode(n, parent, textNodes, htmlId, moduleName, widgets); @@ -502,7 +503,7 @@ uint32_t HtmlManager::load(const std::string& moduleName, const std::string& htm auto path = "/modules/" + moduleName + "/"; auto htmlContent = g_resources.readFileContents(path + htmlPath); - auto root = DataRoot{ parseHtml(htmlContent), nullptr, moduleName }; + auto root = DataRoot{ .node = parseHtml(htmlContent), .dynamicNode = nullptr, .moduleName = moduleName }; if (root.node->getChildren().empty()) return 0; diff --git a/src/framework/html/htmlnode.cpp b/src/framework/html/htmlnode.cpp index 9331018913..bef8408b94 100644 --- a/src/framework/html/htmlnode.cpp +++ b/src/framework/html/htmlnode.cpp @@ -24,6 +24,9 @@ #include #include #include + +#include + #include "htmlparser.h" std::string HtmlNode::getAttr(const std::string& name) const { @@ -360,8 +363,8 @@ void HtmlNode::destroy() { void HtmlNode::remove(const HtmlNodePtr& child) { if (!child) return; - auto it = std::find_if(children.begin(), children.end(), - [&](const HtmlNodePtr& c) { return c.get() == child.get(); }); + auto it = std::ranges::find_if(children, + [&](const HtmlNodePtr& c) { return c.get() == child.get(); }); if (it == children.end()) return; child->unregisterSubtreeFromIndexes(child); @@ -562,7 +565,8 @@ void HtmlNode::setOuterHTML(const std::string& html) { auto rootEl = container ? container->querySelector("div") : nullptr; size_t idx = indexInParent(); - if (idx == size_t(-1)) return; + if (std::cmp_equal(idx, -1)) + return; p->remove(shared_from_this()); diff --git a/src/framework/html/htmlparser.cpp b/src/framework/html/htmlparser.cpp index f5b96ac5f4..92d8a22320 100644 --- a/src/framework/html/htmlparser.cpp +++ b/src/framework/html/htmlparser.cpp @@ -22,6 +22,7 @@ #include "htmlparser.h" #include "htmlnode.h" +#include #include static inline bool is_space(unsigned char c) { return c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '\f'; } @@ -401,8 +402,8 @@ HtmlNodePtr parseHtml(const std::string& html) { while (st.size() > 1) st.pop(); if (!hoistedRaw.empty()) { - for (auto it = hoistedRaw.rbegin(); it != hoistedRaw.rend(); ++it) { - attach_front(root, *it); + for (auto& it : std::ranges::reverse_view(hoistedRaw)) { + attach_front(root, it); } } diff --git a/src/framework/html/queryselector.cpp b/src/framework/html/queryselector.cpp index 34a462ab33..b047553e9b 100644 --- a/src/framework/html/queryselector.cpp +++ b/src/framework/html/queryselector.cpp @@ -94,8 +94,7 @@ struct Selector static std::vector tokenize(const std::string& s) { std::vector tokens; std::string cur; int paren = 0, bracket = 0; auto flush = [&] { if (!cur.empty()) { tokens.push_back(cur); cur.clear(); } }; - for (size_t i = 0; i < s.size(); ++i) { - char ch = s[i]; + for (char ch : s) { if (ch == '(') ++paren; else if (ch == ')') --paren; else if (ch == '[') ++bracket; else if (ch == ']') --bracket; if (paren == 0 && bracket == 0 && (ch == '>' || ch == '+' || ch == '~')) { flush(); tokens.emplace_back(1, ch); } else if (paren == 0 && bracket == 0 && isSpace((unsigned char)ch)) { flush(); } else cur.push_back(ch); @@ -135,7 +134,7 @@ struct Selector } } while (i < tok.size() && tok[i] != ']') ++i; if (i < tok.size()) ++i; - s.attrs.push_back({ key,val,op }); + s.attrs.push_back({ .key = key, .val = val, .op = op }); } else if (c == ':') { ++i; size_t ps = i; while (i < tok.size() && tok[i] != ':') ++i; s.pseudos.push_back(tok.substr(ps, i - ps)); } else ++i; @@ -196,15 +195,15 @@ struct Selector if (s < i && v.substr(s, i - s) == a.val) return true; } return false; } - case AttrTest::Op::Prefix: return v.rfind(a.val, 0) == 0; - case AttrTest::Op::Suffix: return v.size() >= a.val.size() && v.compare(v.size() - a.val.size(), a.val.size(), a.val) == 0; + case AttrTest::Op::Prefix: return v.starts_with(a.val); + case AttrTest::Op::Suffix: return v.size() >= a.val.size() && v.ends_with(a.val); case AttrTest::Op::Substr: return v.find(a.val) != std::string::npos; - case AttrTest::Op::DashMatch:return v == a.val || (v.size() > a.val.size() && v.rfind(a.val + "-", 0) == 0); + case AttrTest::Op::DashMatch:return v == a.val || (v.size() > a.val.size() && v.starts_with(a.val + "-")); } return false; } - bool matchesSimple(const HtmlNodePtr& node, const SimpleSelector& s) const { + [[nodiscard]] bool matchesSimple(const HtmlNodePtr& node, const SimpleSelector& s) const { if (!node) return false; const bool isElem = node->getType() == NodeType::Element; @@ -267,12 +266,12 @@ struct Selector } return true; } - if (pseudo.rfind("nth-child(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("nth-child(") && pseudo.back() == ')') { std::string inside = pseudo.substr(10, pseudo.size() - 11); int idx = node->indexAmongElements() + 1; return matchesNth(idx, inside); } - if (pseudo.rfind("nth-last-child(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("nth-last-child(") && pseudo.back() == ')') { std::string inside = pseudo.substr(15, pseudo.size() - 16); int idx = 0, total = 0; if (auto p = node->getParent()) { @@ -295,12 +294,12 @@ struct Selector for (auto it = p->getChildren().rbegin(); it != p->getChildren().rend(); ++it) if ((*it)->getType() == NodeType::Element && (*it)->getTag() == node->getTag()) return (*it).get() == node.get(); } return false; } - if (pseudo.rfind("nth-of-type(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("nth-of-type(") && pseudo.back() == ')') { std::string inside = pseudo.substr(12, pseudo.size() - 13); int idx = node->indexAmongType() + 1; return matchesNth(idx, inside); } - if (pseudo.rfind("nth-last-of-type(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("nth-last-of-type(") && pseudo.back() == ')') { std::string inside = pseudo.substr(17, pseudo.size() - 18); int idx = 0, total = 0; if (auto p = node->getParent()) { @@ -313,7 +312,7 @@ struct Selector int lastIdx = (total - idx) + 1; return matchesNth(lastIdx, inside); } - if (pseudo.rfind("not(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("not(") && pseudo.back() == ')') { std::string inside = pseudo.substr(4, pseudo.size() - 5); for (const auto& part : splitSelectorList(inside)) { const Selector& neg = getOrParseSelector(part); @@ -321,21 +320,21 @@ struct Selector } return true; } - if (pseudo.rfind("is(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("is(") && pseudo.back() == ')') { std::string inside = pseudo.substr(3, pseudo.size() - 4); for (const auto& part : splitSelectorList(inside)) { const Selector& tmp = getOrParseSelector(part); if (!tmp.steps.empty() && matchesSimple(node, tmp.steps[0].simple)) return true; } return false; } - if (pseudo.rfind("where(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("where(") && pseudo.back() == ')') { std::string inside = pseudo.substr(6, pseudo.size() - 7); for (const auto& part : splitSelectorList(inside)) { const Selector& tmp = getOrParseSelector(part); if (!tmp.steps.empty() && matchesSimple(node, tmp.steps[0].simple)) return true; } return false; } - if (pseudo.rfind("has(", 0) == 0 && pseudo.back() == ')') { + if (pseudo.starts_with("has(") && pseudo.back() == ')') { std::string inside = pseudo.substr(4, pseudo.size() - 5); const Selector& inner = getOrParseSelector(inside); if (inner.steps.empty()) return false; diff --git a/src/framework/luaengine/luaexception.h b/src/framework/luaengine/luaexception.h index efdcc41a38..78b090dd54 100644 --- a/src/framework/luaengine/luaexception.h +++ b/src/framework/luaengine/luaexception.h @@ -32,7 +32,7 @@ class LuaException : public stdext::exception void generateLuaErrorMessage(std::string_view error, int traceLevel); - const char* what() const noexcept override { return m_what.data(); } + [[nodiscard]] const char* what() const noexcept override { return m_what.data(); } protected: LuaException() = default; diff --git a/src/framework/luaengine/luainterface.h b/src/framework/luaengine/luainterface.h index df2c9a0e9c..d20135e6b7 100644 --- a/src/framework/luaengine/luainterface.h +++ b/src/framework/luaengine/luainterface.h @@ -228,7 +228,7 @@ class LuaInterface template R callGlobalField(std::string_view global, std::string_view field, const T&... args); - bool isInCppCallback() const { return m_cppCallbackDepth != 0; } + [[nodiscard]] bool isInCppCallback() const { return m_cppCallbackDepth != 0; } private: /// Load scripts requested by lua 'require' @@ -277,7 +277,7 @@ class LuaInterface void useValue() { pushValue(); ref(); } const char* typeName(int index = -1); - std::string functionSourcePath() const; + [[nodiscard]] std::string functionSourcePath() const; void insert(int index); void remove(int index); @@ -289,7 +289,7 @@ class LuaInterface void getRef(int ref) const; void getWeakRef(int weakRef); - int getGlobalEnvironment() const { return m_globalEnv; } + [[nodiscard]] int getGlobalEnvironment() const { return m_globalEnv; } void setGlobalEnvironment(int env); void resetGlobalEnvironment() { setGlobalEnvironment(m_globalEnv); } @@ -317,7 +317,7 @@ class LuaInterface void newTable() const; void createTable(int narr, int nrec) const; - void* newUserdata(int size) const; + [[nodiscard]] void* newUserdata(int size) const; void pop(int n = 1); long popInteger(); @@ -325,7 +325,7 @@ class LuaInterface bool popBoolean(); std::string popString(); void* popUserdata(); - void* popUpvalueUserdata() const; + [[nodiscard]] void* popUpvalueUserdata() const; LuaObjectPtr popObject(); void pushNil(); @@ -358,8 +358,8 @@ class LuaInterface void* toUserdata(int index = -1); LuaObjectPtr toObject(int index = -1); - int getTop() const; - int stackSize() const { return getTop(); } + [[nodiscard]] int getTop() const; + [[nodiscard]] int stackSize() const { return getTop(); } void clearStack() { pop(stackSize()); } bool hasIndex(const int index) { return (stackSize() >= (index < 0 ? -index : index) && index != 0); } diff --git a/src/framework/luaengine/luavaluecasts.h b/src/framework/luaengine/luavaluecasts.h index c76c798ad1..aa47360dc5 100644 --- a/src/framework/luaengine/luavaluecasts.h +++ b/src/framework/luaengine/luavaluecasts.h @@ -97,7 +97,7 @@ inline bool luavalue_cast(const int index, int64_t& v) const bool r = luavalue_cast(index, d); v = d; return r; } -using lua_u64 = std::conditional_t; +using lua_u64 = std::conditional_t; using lua_unsigned_long = lua_u64; static_assert(sizeof(lua_u64) == 8, "lua_u64 must be 64-bit"); @@ -127,15 +127,17 @@ inline bool luavalue_cast(const int index, unsigned long& v) return r; } -template, int> = 0> +template inline int push_luavalue(lua_u64 v) + requires (!std::is_same_v) { push_luavalue(static_cast(v)); return 1; } -template, int> = 0> +template inline bool luavalue_cast(const int idx, lua_u64& v) + requires (!std::is_same_v) { double d; const bool r = luavalue_cast(idx, d); diff --git a/src/framework/net/connection.cpp b/src/framework/net/connection.cpp index cb190226be..f9b160ee2d 100644 --- a/src/framework/net/connection.cpp +++ b/src/framework/net/connection.cpp @@ -28,7 +28,6 @@ #include #include -#include #include diff --git a/src/framework/net/outputmessage.cpp b/src/framework/net/outputmessage.cpp index d8ba670740..177ebc8490 100644 --- a/src/framework/net/outputmessage.cpp +++ b/src/framework/net/outputmessage.cpp @@ -106,7 +106,7 @@ void OutputMessage::addPaddingBytes(const int bytes, const uint8_t byte) void OutputMessage::encryptRsa() { const int size = g_crypt.rsaGetSize(); - if (m_messageSize < size) + if (std::cmp_less(m_messageSize, size)) throw stdext::exception("insufficient bytes in buffer to encrypt"); if (!g_crypt.rsaEncrypt(static_cast(m_buffer) + m_writePos - size, size)) @@ -184,4 +184,4 @@ void OutputMessage::prependU16(uint16_t value) uint8_t* OutputMessage::getXteaEncryptionBuffer() { return g_game.getClientVersion() >= 1405 ? getHeaderBuffer() : getDataBuffer() - 2; -} +} \ No newline at end of file diff --git a/src/framework/net/outputmessage.h b/src/framework/net/outputmessage.h index a06b8ad3b0..0efdb99c39 100644 --- a/src/framework/net/outputmessage.h +++ b/src/framework/net/outputmessage.h @@ -79,7 +79,7 @@ class OutputMessage final : public LuaObject bool canWrite(int bytes) const; void checkWrite(int bytes); - uint8_t m_maxHeaderSize { 8 }; + uint8_t m_maxHeaderSize{ 8 }; uint16_t m_headerPos{ m_maxHeaderSize }; uint16_t m_writePos{ m_maxHeaderSize }; uint16_t m_messageSize{ 0 }; diff --git a/src/framework/net/packet_player.cpp b/src/framework/net/packet_player.cpp index 24fb21ed54..d1167b2cf7 100644 --- a/src/framework/net/packet_player.cpp +++ b/src/framework/net/packet_player.cpp @@ -53,9 +53,9 @@ PacketPlayer::PacketPlayer(const std::string_view& file) } auto packet = std::make_shared>(packetStr.begin(), packetStr.end()); if (type == "<") { - m_input.push_back(std::make_pair(time, packet)); + m_input.emplace_back(time, packet); } else if (type == ">") { - m_output.push_back(std::make_pair(time, packet)); + m_output.emplace_back(time, packet); } } } @@ -66,7 +66,7 @@ void PacketPlayer::start(std::function m_start = g_clock.millis(); m_recvCallback = recvCallback; m_disconnectCallback = disconnectCallback; - m_event = g_dispatcher.scheduleEvent(std::bind(&PacketPlayer::process, this), 50); + m_event = g_dispatcher.scheduleEvent([this] { process(); }, 50); } void PacketPlayer::stop() @@ -97,7 +97,7 @@ void PacketPlayer::process() } if (!m_input.empty() && nextPacket > 1) { - m_event = g_dispatcher.scheduleEvent(std::bind(&PacketPlayer::process, this), nextPacket); + m_event = g_dispatcher.scheduleEvent([this] { process(); }, nextPacket); } else { m_disconnectCallback(asio::error::eof); stop(); diff --git a/src/framework/net/packet_player.h b/src/framework/net/packet_player.h index 96cd55cb02..a078b053d9 100644 --- a/src/framework/net/packet_player.h +++ b/src/framework/net/packet_player.h @@ -26,10 +26,11 @@ #include #include -class PacketPlayer : public LuaObject { +class PacketPlayer : public LuaObject +{ public: PacketPlayer(const std::string_view& file); - virtual ~PacketPlayer(); + ~PacketPlayer() override; void start(std::function>)> recvCallback, std::function disconnectCallback); void stop(); diff --git a/src/framework/net/packet_recorder.cpp b/src/framework/net/packet_recorder.cpp index 704bb56243..a3b211f904 100644 --- a/src/framework/net/packet_recorder.cpp +++ b/src/framework/net/packet_recorder.cpp @@ -40,9 +40,7 @@ PacketRecorder::PacketRecorder(const std::string_view& file) } PacketRecorder::~PacketRecorder() -{ - -} += default; void PacketRecorder::addInputPacket(const InputMessagePtr& packet) { @@ -66,4 +64,4 @@ void PacketRecorder::addOutputPacket(const OutputMessagePtr& packet) m_stream << std::setfill('0') << std::setw(2) << std::hex << (uint16_t)(uint8_t)buffer; } m_stream << std::dec << "\n"; -} +} \ No newline at end of file diff --git a/src/framework/net/packet_recorder.h b/src/framework/net/packet_recorder.h index e828400ab2..b336fe900c 100644 --- a/src/framework/net/packet_recorder.h +++ b/src/framework/net/packet_recorder.h @@ -25,10 +25,11 @@ #include #include -class PacketRecorder : public LuaObject { +class PacketRecorder : public LuaObject +{ public: PacketRecorder(const std::string_view& file); - virtual ~PacketRecorder(); + ~PacketRecorder() override; void addInputPacket(const InputMessagePtr& packet); void addOutputPacket(const OutputMessagePtr& packet); diff --git a/src/framework/net/protocol.cpp b/src/framework/net/protocol.cpp index 2d1abffcb6..23e20c5436 100644 --- a/src/framework/net/protocol.cpp +++ b/src/framework/net/protocol.cpp @@ -419,14 +419,14 @@ void Protocol::onLocalDisconnected(std::error_code ec) if (m_disconnected) return; auto self(asProtocol()); - #ifndef __EMSCRIPTEN__ +#ifndef __EMSCRIPTEN__ post(g_ioService, [&, ec] { if (m_disconnected) return; m_disconnected = true; onError(ec); }); - #endif +#endif } void Protocol::onPlayerPacket(const std::shared_ptr>& packet) @@ -434,7 +434,7 @@ void Protocol::onPlayerPacket(const std::shared_ptr>& packe if (m_disconnected) return; auto self(asProtocol()); - #ifndef __EMSCRIPTEN__ +#ifndef __EMSCRIPTEN__ post(g_ioService, [&, packet] { if (m_disconnected) return; @@ -445,7 +445,7 @@ void Protocol::onPlayerPacket(const std::shared_ptr>& packe m_inputMessage->setMessageSize(packet->size()); onRecv(m_inputMessage); }); - #endif +#endif } void Protocol::playRecord(PacketPlayerPtr player) @@ -464,4 +464,4 @@ void Protocol::playRecord(PacketPlayerPtr player) void Protocol::setRecorder(PacketRecorderPtr recorder) { m_recorder = recorder; -} +} \ No newline at end of file diff --git a/src/framework/net/protocolhttp.cpp b/src/framework/net/protocolhttp.cpp index 20187d16ea..b236b7d72f 100644 --- a/src/framework/net/protocolhttp.cpp +++ b/src/framework/net/protocolhttp.cpp @@ -23,7 +23,6 @@ #include #include -#include #include #include "protocolhttp.h" @@ -310,7 +309,7 @@ void HttpSession::on_resolve(const std::error_code& ec, asio::ip::tcp::resolver: const auto& endpoint_to_use = (ipv4_it != end) ? ipv4_it : iterator; g_logger.debug("Attempting connection to: {}:{}", instance_uri.domain, instance_uri.port); - + if (instance_uri.port == "443") { // For HTTPS, use the SSL stream's underlying socket m_ssl.lowest_layer().async_connect(*endpoint_to_use, [sft = shared_from_this()]( @@ -342,7 +341,7 @@ void HttpSession::on_connect(const std::error_code& ec) m_ssl.set_verify_callback([](bool, const asio::ssl::verify_context&) { return true; }); - + // Set SNI (Server Name Indication) if (!SSL_set_tlsext_host_name(m_ssl.native_handle(), instance_uri.domain.c_str())) { const std::error_code _ec{ static_cast(ERR_get_error()), asio::error::get_ssl_category() }; @@ -350,7 +349,7 @@ void HttpSession::on_connect(const std::error_code& ec) onError("HttpSession on SSL_set_tlsext_host_name unable to handshake " + m_url + ": " + _ec.message()); return; } - + g_logger.debug("SNI hostname set to: {}", instance_uri.domain); m_ssl.async_handshake(asio::ssl::stream_base::client, @@ -376,7 +375,7 @@ void HttpSession::on_write() { g_logger.debug("Sending HTTP request to: {}:{}", instance_uri.domain, instance_uri.port); g_logger.debug("Request headers: {}", m_request.substr(0, std::min(m_request.length(), size_t(200)))); - + if (instance_uri.port == "443") { async_write(m_ssl, asio::buffer(m_request), [sft = shared_from_this()] (const std::error_code& ec, const size_t bytes) { sft->on_request_sent(ec, bytes); }); @@ -484,7 +483,7 @@ void HttpSession::on_read(const std::error_code& ec, const size_t bytes_transfer m_timer.cancel(); const auto& data = m_response.data(); m_result->response.append(buffers_begin(data), buffers_end(data)); - g_logger.debug("HTTP response received ({} bytes): {}", m_result->response.size(), m_result->response); + g_logger.debug("HTTP response received ({} bytes): {}", m_result->response.size(), m_result->response); m_result->finished = true; m_callback(m_result); }; @@ -1051,7 +1050,7 @@ void WebsocketSession::send(const std::string& data, const uint8_t ws_opcode) ws_frame.push_back(127 + 128); } - for (auto c = num_bytes - 1; c != static_cast(-1); c--) + for (auto c = num_bytes - 1; std::cmp_not_equal(c, -1); c--) ws_frame.push_back((static_cast(length) >> (8 * c)) % 256); } @@ -1127,7 +1126,7 @@ void WebsocketSession::close() }); } } catch (...) { - // + // } } else { try { diff --git a/src/framework/net/protocolhttp.h b/src/framework/net/protocolhttp.h index 1efdc32543..4b325173dd 100644 --- a/src/framework/net/protocolhttp.h +++ b/src/framework/net/protocolhttp.h @@ -80,7 +80,7 @@ class HttpSession : public std::enable_shared_from_this { assert(m_callback != nullptr); assert(m_result != nullptr); - + // Configure SSL context properly m_context.set_default_verify_paths(); m_context.set_verify_mode(asio::ssl::verify_none); @@ -212,7 +212,7 @@ class Http bool wsClose(int operationId); bool cancel(int id); - const std::unordered_map& downloads() const { return m_downloads; } + [[nodiscard]] const std::unordered_map& downloads() const { return m_downloads; } void clearDownloads() { m_downloads.clear(); } diff --git a/src/framework/otml/otmlexception.h b/src/framework/otml/otmlexception.h index 4bae8ca0b5..187c217917 100644 --- a/src/framework/otml/otmlexception.h +++ b/src/framework/otml/otmlexception.h @@ -32,7 +32,7 @@ class OTMLException final : public stdext::exception OTMLException(const OTMLDocumentPtr& doc, std::string_view error, int line = -1); ~OTMLException() noexcept override = default; - const char* what() const noexcept override { return m_what.data(); } + [[nodiscard]] const char* what() const noexcept override { return m_what.data(); } protected: std::string m_what; diff --git a/src/framework/otml/otmlparser.h b/src/framework/otml/otmlparser.h index 816c9bbb3f..e8dc76cd00 100644 --- a/src/framework/otml/otmlparser.h +++ b/src/framework/otml/otmlparser.h @@ -36,7 +36,7 @@ class OTMLParser /// Retrieve next line from the input stream std::string getNextLine(); /// Counts depth of a line (every 2 spaces increments one depth) - int getLineDepth(std::string_view line, bool multilining = false) const; + [[nodiscard]] int getLineDepth(std::string_view line, bool multilining = false) const; /// Parse each line of the input stream void parseLine(std::string line); diff --git a/src/framework/pch.cpp b/src/framework/pch.cpp index 2a73de2890..79187a5b79 100644 --- a/src/framework/pch.cpp +++ b/src/framework/pch.cpp @@ -20,4 +20,4 @@ * THE SOFTWARE. */ -#include "pch.h" +#include "pch.h" \ No newline at end of file diff --git a/src/framework/pch.h b/src/framework/pch.h index 11ab6774be..01c988b6cb 100644 --- a/src/framework/pch.h +++ b/src/framework/pch.h @@ -50,7 +50,7 @@ #include #include #include - +#include #include #include @@ -66,8 +66,9 @@ // FMT Custom Formatter for Enums template -std::enable_if_t, std::underlying_type_t> -format_as(E e) { +std::underlying_type_t +format_as(E e) requires (std::is_enum_v) +{ return static_cast>(e); } diff --git a/src/framework/platform/platform.h b/src/framework/platform/platform.h index b8ab55df74..8d92cc8e07 100644 --- a/src/framework/platform/platform.h +++ b/src/framework/platform/platform.h @@ -88,7 +88,7 @@ class Platform return m_device.type == Mobile; #else return MAIN_THREAD_EM_ASM_INT({ - return (/iphone|ipod|ipad|android/i).test(navigator.userAgent); + return (/ iphone | ipod | ipad | android / i).test(navigator.userAgent); }) == 1; #endif } diff --git a/src/framework/platform/platformwindow.h b/src/framework/platform/platformwindow.h index 5f2c04c1c2..a1b009b245 100644 --- a/src/framework/platform/platformwindow.h +++ b/src/framework/platform/platformwindow.h @@ -27,10 +27,10 @@ #include #include -// Forward declaration + // Forward declaration class Color; - //@bindsingleton g_window +//@bindsingleton g_window class PlatformWindow { enum @@ -92,7 +92,7 @@ class PlatformWindow void setTitleBarColor(int r, int g, int b); void setTitleBarColor(float r, float g, float b); void setTitleBarColorRGB(uint8_t r, uint8_t g, uint8_t b); - + virtual Size getDisplaySize() = 0; virtual std::string getClipboardText() = 0; virtual std::string getPlatformType() = 0; @@ -122,7 +122,7 @@ class PlatformWindow bool isFullscreen() { return m_fullscreen; } bool hasFocus() { return m_focused; } - bool vsyncEnabled() const { return m_vsync; } + [[nodiscard]] bool vsyncEnabled() const { return m_vsync; } void setOnClose(const std::function& onClose) { m_onClose = onClose; } void setOnResize(const OnResizeCallback& onResize) { m_onResize = onResize; } diff --git a/src/framework/platform/win32window.cpp b/src/framework/platform/win32window.cpp index a0aec071d2..480e3d319b 100644 --- a/src/framework/platform/win32window.cpp +++ b/src/framework/platform/win32window.cpp @@ -34,8 +34,9 @@ #include #endif -// Include for DWM API + // Include for DWM API #include + #pragma comment(lib, "dwmapi.lib") #define HSB_BIT_SET(p, n) (p[(n)/8] |= (128 >>((n)%8))) @@ -46,7 +47,7 @@ constexpr auto WINDOW_NAME = "BASED_ON_TIBIA_GAME_ENGINE"; #ifndef DWMWA_CAPTION_COLOR #define DWMWA_CAPTION_COLOR 35 #endif -#ifndef DWMWA_TEXT_COLOR +#ifndef DWMWA_TEXT_COLOR #define DWMWA_TEXT_COLOR 36 #endif @@ -893,7 +894,8 @@ int WIN32Window::internalLoadMouseCursor(const ImagePtr& image, const Point& hot void WIN32Window::setMouseCursor(int cursorId) { g_mainDispatcher.addEvent([&, cursorId] { - if (cursorId >= static_cast(m_cursors.size()) || cursorId < 0) + if (std::cmp_greater_equal(cursorId, m_cursors.size()) + || cursorId < 0) return; m_cursor = m_cursors[cursorId]; @@ -1052,7 +1054,7 @@ void WIN32Window::setTitleBarColor(const Color& color) // Color uses RGBA format, Windows expects BGR const COLORREF dwmColor = RGB( static_cast(color.r() * 255), - static_cast(color.g() * 255), + static_cast(color.g() * 255), static_cast(color.b() * 255) ); @@ -1069,7 +1071,7 @@ void WIN32Window::setTitleBarColor(const Color& color) // This is normal on older Windows versions g_logger.debug("Failed to set title bar color: HRESULT = 0x{:08X}", static_cast(hr)); } else { - g_logger.debug("Successfully set title bar color to RGB({}, {}, {})", + g_logger.debug("Successfully set title bar color to RGB({}, {}, {})", static_cast(color.r() * 255), static_cast(color.g() * 255), static_cast(color.b() * 255) diff --git a/src/framework/platform/win32window.h b/src/framework/platform/win32window.h index d5d56344b9..4b85d672ed 100644 --- a/src/framework/platform/win32window.h +++ b/src/framework/platform/win32window.h @@ -83,9 +83,9 @@ class WIN32Window : public PlatformWindow int internalLoadMouseCursor(const ImagePtr& image, const Point& hotSpot) override; private: - Rect getClientRect() const; + [[nodiscard]] Rect getClientRect() const; Rect getWindowRect(); - Rect adjustWindowRect(const Rect& rect) const; + [[nodiscard]] Rect adjustWindowRect(const Rect& rect) const; std::vector m_cursors; HWND m_window; diff --git a/src/framework/sound/soundmanager.cpp b/src/framework/sound/soundmanager.cpp index 918dd1ba0b..b401e1d033 100644 --- a/src/framework/sound/soundmanager.cpp +++ b/src/framework/sound/soundmanager.cpp @@ -443,14 +443,14 @@ bool SoundManager::loadFromProtobuf(const std::string& directory, const std::str uint32_t effectId = protobufSoundEffect.id(); m_clientSoundEffects.emplace(effectId, ClientSoundEffect{ - effectId, - static_cast(protobufSoundEffect.numeric_sound_type()), - pitch.min_value(), - pitch.max_value(), - volume.max_value(), - volume.max_value(), - protobufSoundEffect.has_simple_sound_effect() ? protobufSoundEffect.simple_sound_effect().sound_id() : 0, - std::move(randomSounds) + .clientId = effectId, + .type = static_cast(protobufSoundEffect.numeric_sound_type()), + .pitchMin = pitch.min_value(), + .pitchMax = pitch.max_value(), + .volumeMin = volume.max_value(), + .volumeMax = volume.max_value(), + .soundId = protobufSoundEffect.has_simple_sound_effect() ? protobufSoundEffect.simple_sound_effect().sound_id() : 0, + .randomSoundId = std::move(randomSounds) }); } @@ -459,13 +459,13 @@ bool SoundManager::loadFromProtobuf(const std::string& directory, const std::str uint32_t effectId = protobufLocationAmbient.id(); DelayedSoundEffects effects = {}; for (const auto& delayedEffect : protobufLocationAmbient.delayed_effects()) { - effects.push_back({ delayedEffect.numeric_sound_effect_id(), delayedEffect.delay_seconds() }); + effects.emplace_back(delayedEffect.numeric_sound_effect_id(), delayedEffect.delay_seconds()); } m_clientAmbientEffects.emplace(effectId, ClientLocationAmbient{ - effectId, - protobufLocationAmbient.looping_sound_id(), - std::move(effects) + .clientId = effectId, + .loopedAudioFileId = protobufLocationAmbient.looping_sound_id(), + .delayedSoundEffects = std::move(effects) }); } @@ -478,14 +478,14 @@ bool SoundManager::loadFromProtobuf(const std::string& directory, const std::str ItemCountSoundEffects soundEffects = {}; for (const auto& soundEffect : protobufItemAmbient.sound_effects()) { - soundEffects.push_back({ soundEffect.looping_sound_id(), soundEffect.count() }); + soundEffects.emplace_back(soundEffect.looping_sound_id(), soundEffect.count()); } uint32_t effectId = protobufItemAmbient.id(); m_clientItemAmbientEffects.emplace(effectId, ClientItemAmbient{ - effectId, - std::move(itemClientIds), - std::move(soundEffects) + .id = effectId, + .clientIds = std::move(itemClientIds), + .itemCountSoundEffects = std::move(soundEffects) }); } @@ -493,9 +493,9 @@ bool SoundManager::loadFromProtobuf(const std::string& directory, const std::str for (const auto& protobufMusicTemplate : protobufSounds.music_template()) { uint32_t effectId = protobufMusicTemplate.id(); m_clientMusic.emplace(effectId, ClientMusic{ - effectId, - protobufMusicTemplate.sound_id(), - static_cast(protobufMusicTemplate.music_type()) + .id = effectId, + .audioFileId = protobufMusicTemplate.sound_id(), + .musicType = static_cast(protobufMusicTemplate.music_type()) }); } diff --git a/src/framework/sound/soundmanager.h b/src/framework/sound/soundmanager.h index 23afb9069f..040f26be1a 100644 --- a/src/framework/sound/soundmanager.h +++ b/src/framework/sound/soundmanager.h @@ -113,7 +113,7 @@ struct ClientMusic ClientMusicType musicType; }; - //@bindsingleton g_sounds +//@bindsingleton g_sounds class SoundManager { enum diff --git a/src/framework/stdext/cast.h b/src/framework/stdext/cast.h index a1e601638e..e3d50a3c4f 100644 --- a/src/framework/stdext/cast.h +++ b/src/framework/stdext/cast.h @@ -146,7 +146,7 @@ namespace stdext m_what = ss.str(); } - const char* what() const noexcept override { return m_what.c_str(); } + [[nodiscard]] const char* what() const noexcept override { return m_what.c_str(); } private: std::string m_what; }; diff --git a/src/framework/stdext/exception.h b/src/framework/stdext/exception.h index a292d1f2ed..a0796e0436 100644 --- a/src/framework/stdext/exception.h +++ b/src/framework/stdext/exception.h @@ -40,7 +40,7 @@ namespace stdext exception(fmt::format_string fmtStr, Args&&... args) : m_what(fmt::format(fmtStr, std::forward(args)...)) {} ~exception() noexcept override = default; - const char* what() const noexcept override { return m_what.data(); } + [[nodiscard]] const char* what() const noexcept override { return m_what.data(); } protected: std::string m_what; }; diff --git a/src/framework/stdext/math.h b/src/framework/stdext/math.h index a79fff40b3..3e83d1625c 100644 --- a/src/framework/stdext/math.h +++ b/src/framework/stdext/math.h @@ -51,5 +51,4 @@ namespace stdext int32_t normal_random(int32_t minNumber, int32_t maxNumber); bool random_bool(double probability = 0.5); std::mt19937& random_gen(); - } diff --git a/src/framework/stdext/qrcodegen.cpp b/src/framework/stdext/qrcodegen.cpp index 3cdb515fbe..432052c283 100644 --- a/src/framework/stdext/qrcodegen.cpp +++ b/src/framework/stdext/qrcodegen.cpp @@ -30,7 +30,6 @@ #include #include #include -#include using std::int8_t; using std::uint8_t; diff --git a/src/framework/stdext/qrcodegen.h b/src/framework/stdext/qrcodegen.h index 4903230598..0cbfdb3d37 100644 --- a/src/framework/stdext/qrcodegen.h +++ b/src/framework/stdext/qrcodegen.h @@ -75,13 +75,14 @@ namespace qrcodegen { /* * (Package-private) Returns the mode indicator bits, which is an unsigned 4-bit value (range 0 to 15). */ - public: int getModeBits() const; + public: + [[nodiscard]] int getModeBits() const; - /* - * (Package-private) Returns the bit width of the character count field for a segment in - * this mode in a QR Code at the given version number. The result is in the range [0, 16]. - */ - int numCharCountBits(int ver) const; + /* + * (Package-private) Returns the bit width of the character count field for a segment in + * this mode in a QR Code at the given version number. The result is in the range [0, 16]. + */ + [[nodiscard]] int numCharCountBits(int ver) const; }; /*---- Static factory functions (mid level) ----*/ @@ -167,17 +168,17 @@ namespace qrcodegen { /* * Returns the mode field of this segment. */ - const Mode& getMode() const; + [[nodiscard]] const Mode& getMode() const; /* * Returns the character count field of this segment. */ - int getNumChars() const; + [[nodiscard]] int getNumChars() const; /* * Returns the data bits of this segment. */ - const std::vector& getData() const; + [[nodiscard]] const std::vector& getData() const; // (Package-private) Calculates the number of bits needed to encode the given segments at // the given version. Returns a non-negative number if successful. Otherwise returns -1 if a @@ -304,29 +305,29 @@ namespace qrcodegen { /* * Returns this QR Code's version, in the range [1, 40]. */ - int getVersion() const; + [[nodiscard]] int getVersion() const; /* * Returns this QR Code's size, in the range [21, 177]. */ - int getSize() const; + [[nodiscard]] int getSize() const; /* * Returns this QR Code's error correction level. */ - Ecc getErrorCorrectionLevel() const; + [[nodiscard]] Ecc getErrorCorrectionLevel() const; /* * Returns this QR Code's mask, in the range [0, 7]. */ - int getMask() const; + [[nodiscard]] int getMask() const; /* * Returns the color of the module (pixel) at the given coordinates, which is false * for light or true for dark. The top left corner has the coordinates (x=0, y=0). * If the given coordinates are out of bounds, then false (light) is returned. */ - bool getModule(int x, int y) const; + [[nodiscard]] bool getModule(int x, int y) const; /*---- Private helper methods for constructor: Drawing function modules ----*/ @@ -354,13 +355,13 @@ namespace qrcodegen { void setFunctionModule(int x, int y, bool isDark); // Returns the color of the module at the given coordinates, which must be in range. - bool module(int x, int y) const; + [[nodiscard]] bool module(int x, int y) const; /*---- Private helper methods for constructor: Codewords and masking ----*/ // Returns a new byte string representing the given data with the appropriate error correction // codewords appended to it, based on this object's version and error correction level. - std::vector addEccAndInterleave(const std::vector& data) const; + [[nodiscard]] std::vector addEccAndInterleave(const std::vector& data) const; // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire // data area of this QR Code. Function modules need to be marked off before this is called. @@ -375,14 +376,14 @@ namespace qrcodegen { // Calculates and returns the penalty score based on state of this QR Code's current modules. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. - long getPenaltyScore() const; + [[nodiscard]] long getPenaltyScore() const; /*---- Private helper functions ----*/ // Returns an ascending list of positions of alignment patterns for this version number. // Each position is in the range [0,177), and are used on both the x and y axes. // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. - std::vector getAlignmentPatternPositions() const; + [[nodiscard]] std::vector getAlignmentPatternPositions() const; // Returns the number of data bits that can be stored in a QR Code of the given version number, after // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. @@ -407,7 +408,7 @@ namespace qrcodegen { // Can only be called immediately after a light run is added, and // returns either 0, 1, or 2. A helper function for getPenaltyScore(). - int finderPenaltyCountPatterns(const std::array& runHistory) const; + [[nodiscard]] int finderPenaltyCountPatterns(const std::array& runHistory) const; // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). int finderPenaltyTerminateAndCount(bool currentRunColor, int currentRunLength, std::array& runHistory) const; diff --git a/src/framework/stdext/storage.h b/src/framework/stdext/storage.h index a6f0f6b98b..31d063fb2b 100644 --- a/src/framework/stdext/storage.h +++ b/src/framework/stdext/storage.h @@ -66,7 +66,7 @@ namespace stdext bool has(const Key& k) const { return m_data.contains(k); } - size_t size() const { return m_data.count(); } + [[nodiscard]] size_t size() const { return m_data.count(); } void clear() { m_data.clear(); } diff --git a/src/framework/stdext/time.h b/src/framework/stdext/time.h index c60c962d1f..f82cad7f99 100644 --- a/src/framework/stdext/time.h +++ b/src/framework/stdext/time.h @@ -35,9 +35,9 @@ namespace stdext struct timer { timer() { restart(); } - float elapsed_seconds() const { return (micros() - m_start) / 1000000.f; } - ticks_t elapsed_millis() const { return (micros() - m_start) / 1000; } - ticks_t elapsed_micros() const { return micros() - m_start; } + [[nodiscard]] float elapsed_seconds() const { return (micros() - m_start) / 1000000.f; } + [[nodiscard]] ticks_t elapsed_millis() const { return (micros() - m_start) / 1000; } + [[nodiscard]] ticks_t elapsed_micros() const { return micros() - m_start; } void restart(const int shift = 0) { m_start = micros() - shift; } private: diff --git a/src/framework/ui/uianchorlayout.h b/src/framework/ui/uianchorlayout.h index 2643ebe336..c18e00ee2a 100644 --- a/src/framework/ui/uianchorlayout.h +++ b/src/framework/ui/uianchorlayout.h @@ -22,8 +22,6 @@ #pragma once -#include - #include "uilayout.h" class UIAnchor : public std::enable_shared_from_this diff --git a/src/framework/ui/uiboxlayout.cpp b/src/framework/ui/uiboxlayout.cpp index 3a48079b43..c414c635ce 100644 --- a/src/framework/ui/uiboxlayout.cpp +++ b/src/framework/ui/uiboxlayout.cpp @@ -23,7 +23,6 @@ #include "uiboxlayout.h" #include "uiwidget.h" -#include UIBoxLayout::UIBoxLayout(UIWidgetPtr parentWidget) : UILayout(std::move(parentWidget)) {} diff --git a/src/framework/ui/uigridlayout.cpp b/src/framework/ui/uigridlayout.cpp index 0b1f77f5e7..f218b58ad2 100644 --- a/src/framework/ui/uigridlayout.cpp +++ b/src/framework/ui/uigridlayout.cpp @@ -25,8 +25,6 @@ #include -#include - UIGridLayout::UIGridLayout(UIWidgetPtr parentWidget) : UILayout(std::move(parentWidget)) {} void UIGridLayout::applyStyle(const OTMLNodePtr& styleNode) diff --git a/src/framework/ui/uihorizontallayout.h b/src/framework/ui/uihorizontallayout.h index fe777f2f56..8f7049c5e0 100644 --- a/src/framework/ui/uihorizontallayout.h +++ b/src/framework/ui/uihorizontallayout.h @@ -22,8 +22,6 @@ #pragma once -#include - #include "uiboxlayout.h" class UIHorizontalLayout final : public UIBoxLayout diff --git a/src/framework/ui/uilayout.h b/src/framework/ui/uilayout.h index 56d34cbcef..5308330869 100644 --- a/src/framework/ui/uilayout.h +++ b/src/framework/ui/uilayout.h @@ -26,8 +26,6 @@ #include #include -#include - // @bindclass class UILayout : public LuaObject { diff --git a/src/framework/ui/uilayoutflexbox.cpp b/src/framework/ui/uilayoutflexbox.cpp index 35662ebd40..414f0e9c22 100644 --- a/src/framework/ui/uilayoutflexbox.cpp +++ b/src/framework/ui/uilayoutflexbox.cpp @@ -1,5 +1,7 @@ #include "uilayoutflexbox.h" +#include + namespace { enum class Axis { Horizontal, Vertical }; @@ -328,7 +330,7 @@ void layoutFlex(UIWidget& container) return; } - std::stable_sort(items.begin(), items.end(), [](const FlexItemData& a, const FlexItemData& b) { + std::ranges::stable_sort(items, [](const FlexItemData& a, const FlexItemData& b) { if (a.order != b.order) return a.order < b.order; return a.sourceIndex < b.sourceIndex; @@ -538,7 +540,7 @@ void layoutFlex(UIWidget& container) for (size_t i = 0; i < lineCount; ++i) lineOrder[i] = i; if (wrapReverse) - std::reverse(lineOrder.begin(), lineOrder.end()); + std::ranges::reverse(lineOrder); std::vector lineOffsets(lineCount, 0.0); double crossCursor = crossLeading; diff --git a/src/framework/ui/uimanager.cpp b/src/framework/ui/uimanager.cpp index 4b472c5146..6719733a89 100644 --- a/src/framework/ui/uimanager.cpp +++ b/src/framework/ui/uimanager.cpp @@ -33,6 +33,8 @@ #include "framework/graphics/graphics.h" #include +#include + UIManager g_ui; void UIManager::init() @@ -286,8 +288,8 @@ void UIManager::updateHoveredWidget(const bool now) for (const auto& p : std::views::reverse(m_hoveredWidgets)) { const auto w = p.get(); - bool still = std::any_of(newHovered.begin(), newHovered.end(), - [&](const UIWidgetPtr& p) { return p.get() == w; }); + bool still = std::ranges::any_of(newHovered, + [&](const UIWidgetPtr& p) { return p.get() == w; }); if (!still) { w->updateState(Fw::HoverState, false); w->onHoverChange(false); @@ -299,8 +301,8 @@ void UIManager::updateHoveredWidget(const bool now) if (!w->isEnabled()) continue; - bool was = std::any_of(m_hoveredWidgets.begin(), m_hoveredWidgets.end(), - [&](const UIWidgetPtr& q) { return q.get() == w; }); + bool was = std::ranges::any_of(m_hoveredWidgets, + [&](const UIWidgetPtr& q) { return q.get() == w; }); if (!was) { w->updateState(Fw::HoverState, true); w->onHoverChange(true); @@ -368,13 +370,13 @@ void UIManager::onWidgetDestroy(const UIWidgetPtr& widget) if (widget->isOnHtml()) { { // Pressed Widgets - auto it = std::find(m_pressedWidgets.begin(), m_pressedWidgets.end(), widget); + auto it = std::ranges::find(m_pressedWidgets, widget); if (it != m_pressedWidgets.end()) { m_pressedWidgets.erase(it); } } { // Hovered Widgets - auto it = std::find(m_hoveredWidgets.begin(), m_hoveredWidgets.end(), widget); + auto it = std::ranges::find(m_hoveredWidgets, widget); if (it != m_hoveredWidgets.end()) { m_hoveredWidgets.erase(it); } diff --git a/src/framework/ui/uitextedit.cpp b/src/framework/ui/uitextedit.cpp index e16e42278e..ea566d35a4 100644 --- a/src/framework/ui/uitextedit.cpp +++ b/src/framework/ui/uitextedit.cpp @@ -171,7 +171,7 @@ void UITextEdit::update(const bool focusCursor, bool disableAreaUpdate) } // resize just on demand - if (textLength > static_cast(m_glyphsCoords.size())) { + if (std::cmp_greater(textLength, m_glyphsCoords.size())) { m_glyphsCoords.resize(textLength); } @@ -656,7 +656,8 @@ std::string UITextEdit::getSelection() void UITextEdit::updateText() { - if (m_cursorPos > static_cast(m_text.length())) + if (std::cmp_greater(m_cursorPos, m_text.length())) + m_cursorPos = m_text.length(); // any text changes reset the selection @@ -778,7 +779,7 @@ bool UITextEdit::onKeyPress(const uint8_t keyCode, const int keyboardModifiers, return true; } } else if (keyCode == Fw::KeyEnd) { // move cursor to last character - if (m_cursorPos != static_cast(m_text.length())) { + if (std::cmp_not_equal(m_cursorPos, m_text.length())) { clearSelection(); setCursorPos(m_text.length()); return true; @@ -869,7 +870,7 @@ bool UITextEdit::onKeyPress(const uint8_t keyCode, const int keyboardModifiers, return true; } } else if (keyCode == Fw::KeyEnd) { // move cursor to last character - if (m_cursorPos != static_cast(m_text.length())) { + if (std::cmp_not_equal(m_cursorPos, m_text.length())) { setSelection(m_cursorPos, m_text.length()); setCursorPos(m_text.length()); return true; diff --git a/src/framework/ui/uitranslator.cpp b/src/framework/ui/uitranslator.cpp index e9ea4b53bc..0e5dd2f1fd 100644 --- a/src/framework/ui/uitranslator.cpp +++ b/src/framework/ui/uitranslator.cpp @@ -128,4 +128,4 @@ Fw::AutoFocusPolicy Fw::translateAutoFocusPolicy(std::string policy) if (policy == "last") return AutoFocusLast; return AutoFocusNone; -} +} \ No newline at end of file diff --git a/src/framework/ui/uiverticallayout.h b/src/framework/ui/uiverticallayout.h index 0334a8d8f7..cf331cf67b 100644 --- a/src/framework/ui/uiverticallayout.h +++ b/src/framework/ui/uiverticallayout.h @@ -22,8 +22,6 @@ #pragma once -#include - #include "uiboxlayout.h" // @bindclass diff --git a/src/framework/ui/uiwidget.cpp b/src/framework/ui/uiwidget.cpp index 59be2e8bf4..ddb17d9efc 100644 --- a/src/framework/ui/uiwidget.cpp +++ b/src/framework/ui/uiwidget.cpp @@ -1414,7 +1414,8 @@ UIWidgetPtr UIWidget::getRootParent() UIWidgetPtr UIWidget::getChildAfter(const UIWidgetPtr& relativeChild) { - return relativeChild->m_childIndex == static_cast(m_children.size()) ? + return std::cmp_equal(relativeChild->m_childIndex, m_children.size()) + ? nullptr : m_children[relativeChild->m_childIndex]; } @@ -2034,7 +2035,7 @@ bool UIWidget::propagateOnKeyPress(const uint8_t keyCode, const int keyboardModi return true; } - if (autoRepeatTicks == 0 || autoRepeatTicks >= m_autoRepeatDelay) + if (autoRepeatTicks == 0 || std::cmp_greater_equal(autoRepeatTicks, m_autoRepeatDelay)) return onKeyPress(keyCode, keyboardModifiers, autoRepeatTicks); return false; } diff --git a/src/framework/ui/uiwidget.h b/src/framework/ui/uiwidget.h index 319a6594fa..37b6b5f2ee 100644 --- a/src/framework/ui/uiwidget.h +++ b/src/framework/ui/uiwidget.h @@ -199,11 +199,11 @@ enum class OverflowType : uint8_t struct SizeUnit { - bool needsUpdate(Unit _unit) const { + [[nodiscard]] bool needsUpdate(Unit _unit) const { return pendingUpdate && unit == _unit; } - bool needsUpdate(Unit _unit, uint32_t _version) const { + [[nodiscard]] bool needsUpdate(Unit _unit, uint32_t _version) const { return pendingUpdate && unit == _unit && version != _version; } @@ -215,7 +215,7 @@ struct SizeUnit SizeUnit() = default; SizeUnit(Unit u) : unit(u) {} - SizeUnit(int16_t v) : unit(Unit::Px), value(v) {} + SizeUnit(int16_t v) : value(v) {} SizeUnit(Unit u, int16_t v, int16_t valueCalculed, uint32_t needUpdate) : unit(u), value(v), valueCalculed(valueCalculed), pendingUpdate(needUpdate) {} @@ -663,7 +663,9 @@ class UIWidget : public LuaObject bool isEffectivelyVisible() { return isVisible() || m_displayType != DisplayType::None; } bool isFirstChild() { return m_parent && m_childIndex == 1; } - bool isLastChild() { return m_parent && m_childIndex == static_cast(m_parent->m_children.size()); } + bool isLastChild() { + return m_parent && std::cmp_equal(m_childIndex, m_parent->m_children.size()); + } bool isMiddleChild() { return !isFirstChild() && !isLastChild(); } bool hasChildren() { return !m_children.empty(); } diff --git a/src/framework/ui/uiwidgetbasestyle.cpp b/src/framework/ui/uiwidgetbasestyle.cpp index 5c8595af38..894052b4b2 100644 --- a/src/framework/ui/uiwidgetbasestyle.cpp +++ b/src/framework/ui/uiwidgetbasestyle.cpp @@ -203,13 +203,13 @@ namespace { if (lower == "auto") { widget->setFlexGrow(1.f); widget->setFlexShrink(1.f); - widget->setFlexBasis({ FlexBasis::Type::Auto, 0.f }); + widget->setFlexBasis({ .type = FlexBasis::Type::Auto, .value = 0.f }); return; } if (lower == "none") { widget->setFlexGrow(0.f); widget->setFlexShrink(0.f); - widget->setFlexBasis({ FlexBasis::Type::Auto, 0.f }); + widget->setFlexBasis({ .type = FlexBasis::Type::Auto, .value = 0.f }); return; } } diff --git a/src/framework/ui/uiwidgethtml.cpp b/src/framework/ui/uiwidgethtml.cpp index 220c4a9461..57451007c4 100644 --- a/src/framework/ui/uiwidgethtml.cpp +++ b/src/framework/ui/uiwidgethtml.cpp @@ -803,7 +803,7 @@ void UIWidget::applyDimension(bool isWidth, std::string valueStr) { int16_t num = stdext::to_number(std::string(numericPart(sv))); applyDimension(isWidth, unit, num); if (m_htmlNode) - m_htmlNode->getStyles()["styles"][isWidth ? "width" : "height"] = { valueStr , "" }; + m_htmlNode->getStyles()["styles"][isWidth ? "width" : "height"] = { .value = valueStr , .inheritedFromId = "" }; } void UIWidget::applyDimension(bool isWidth, Unit unit, int16_t value) { @@ -1027,13 +1027,13 @@ void UIWidget::updateTableLayout() const int outerHeight = std::max(0, cellHeight) + cell->m_padding.top + cell->m_padding.bottom; rowCellInfo[rowIndex].push_back(TableCellInfo{ - cell, - columnIndex, - colSpan, - effectiveRowSpan, - candidate, - fixedWidth, - outerHeight, + .widget = cell, + .column = columnIndex, + .columnSpan = colSpan, + .rowSpan = effectiveRowSpan, + .requiredOuterWidth = candidate, + .widthFixed = fixedWidth, + .outerHeight = outerHeight, }); const std::size_t occupancyValue = effectiveRowSpan; @@ -1055,8 +1055,8 @@ void UIWidget::updateTableLayout() std::vector columnWidths(columnCount, 0); std::vector columnFixed(columnCount, false); - for (std::size_t rowIndex = 0; rowIndex < rowCellInfo.size(); ++rowIndex) { - for (const auto& info : rowCellInfo[rowIndex]) { + for (auto& rowIndex : rowCellInfo) { + for (const auto& info : rowIndex) { const std::size_t span = std::min(info.columnSpan, columnCount - info.column); if (span == 0) continue; diff --git a/src/framework/util/color.h b/src/framework/util/color.h index e335367a07..29fee8dc27 100644 --- a/src/framework/util/color.h +++ b/src/framework/util/color.h @@ -49,18 +49,18 @@ class Color update(); } - constexpr uint8_t a() const { return static_cast(m_a * 255.f); } - constexpr uint8_t b() const { return static_cast(m_b * 255.f); } - constexpr uint8_t g() const { return static_cast(m_g * 255.f); } - constexpr uint8_t r() const { return static_cast(m_r * 255.f); } - - constexpr float aF() const { return m_a; } - constexpr float bF() const { return m_b; } - constexpr float gF() const { return m_g; } - constexpr float rF() const { return m_r; } - - constexpr uint32_t rgba() const { return static_cast(a() << 24 | b() << 16 | g() << 8 | r()); } - constexpr size_t hash() const { return m_hash; } + [[nodiscard]] constexpr uint8_t a() const { return static_cast(m_a * 255.f); } + [[nodiscard]] constexpr uint8_t b() const { return static_cast(m_b * 255.f); } + [[nodiscard]] constexpr uint8_t g() const { return static_cast(m_g * 255.f); } + [[nodiscard]] constexpr uint8_t r() const { return static_cast(m_r * 255.f); } + + [[nodiscard]] constexpr float aF() const { return m_a; } + [[nodiscard]] constexpr float bF() const { return m_b; } + [[nodiscard]] constexpr float gF() const { return m_g; } + [[nodiscard]] constexpr float rF() const { return m_r; } + + [[nodiscard]] constexpr uint32_t rgba() const { return static_cast(a() << 24 | b() << 16 | g() << 8 | r()); } + [[nodiscard]] constexpr size_t hash() const { return m_hash; } void setRed(const int r) { m_r = static_cast(r) / 255.f; update(); } void setGreen(const int g) { m_g = static_cast(g) / 255.f; update(); } diff --git a/src/framework/util/crypt.cpp b/src/framework/util/crypt.cpp index f61a62cb39..c77daa750e 100644 --- a/src/framework/util/crypt.cpp +++ b/src/framework/util/crypt.cpp @@ -299,4 +299,4 @@ std::string Crypt::sha1Encrypt(const std::string& input) { oss << std::hex << std::setw(2) << std::setfill('0') << static_cast(byte); return oss.str(); -} +} \ No newline at end of file diff --git a/src/framework/util/crypt.h b/src/framework/util/crypt.h index deeb2e2511..cc8df73a51 100644 --- a/src/framework/util/crypt.h +++ b/src/framework/util/crypt.h @@ -65,7 +65,7 @@ class Crypt private: std::string _encrypt(const std::string& decrypted_string, bool useMachineUUID); std::string _decrypt(const std::string& encrypted_string, bool useMachineUUID); - std::string getCryptKey(bool useMachineUUID) const; + [[nodiscard]] std::string getCryptKey(bool useMachineUUID) const; uuids::uuid m_machineUUID; diff --git a/src/framework/util/matrix.h b/src/framework/util/matrix.h index 2d88d31206..8896d84a2d 100644 --- a/src/framework/util/matrix.h +++ b/src/framework/util/matrix.h @@ -37,16 +37,16 @@ class Matrix Matrix(const U* values) { *this = values; } void setIdentity(); - bool isIdentity() const; + [[nodiscard]] bool isIdentity() const; void fill(T value); - size_t hash() const { return m_hash; } + [[nodiscard]] size_t hash() const { return m_hash; } - Matrix transposed() const; + [[nodiscard]] Matrix transposed() const; std::enable_if_t transpose() { *this = transposed(); } T* data() { return m[0]; } - const T* data() const { return m[0]; } + [[nodiscard]] const T* data() const { return m[0]; } T& operator()(const int row, const int column) { return m[row - 1][column - 1]; } T operator()(const int row, const int column) const { return m[row - 1][column - 1]; } diff --git a/src/framework/util/point.h b/src/framework/util/point.h index 154edb6d78..dd560bb5cd 100644 --- a/src/framework/util/point.h +++ b/src/framework/util/point.h @@ -38,12 +38,12 @@ class TPoint constexpr TPoint(T x, T y) : x{ x }, y{ y } {} constexpr TPoint(T xy) : x{ xy }, y{ xy } {} - constexpr bool isNull() const noexcept { return x == 0 && y == 0; } - constexpr T manhattanLength() const noexcept { return std::abs(x) + std::abs(y); } - constexpr float length() const noexcept { return std::sqrt(static_cast(x * x + y * y)); } - constexpr float distanceFrom(const TPoint& other) const noexcept { return (*this - other).length(); } - constexpr TPoint translated(T dx, T dy) const noexcept { return { x + dx, y + dy }; } - constexpr TSize toSize() const noexcept { return { x, y }; } + [[nodiscard]] constexpr bool isNull() const noexcept { return x == 0 && y == 0; } + [[nodiscard]] constexpr T manhattanLength() const noexcept { return std::abs(x) + std::abs(y); } + [[nodiscard]] constexpr float length() const noexcept { return std::sqrt(static_cast(x * x + y * y)); } + [[nodiscard]] constexpr float distanceFrom(const TPoint& other) const noexcept { return (*this - other).length(); } + [[nodiscard]] constexpr TPoint translated(T dx, T dy) const noexcept { return { x + dx, y + dy }; } + [[nodiscard]] constexpr TSize toSize() const noexcept { return { x, y }; } constexpr TPoint scale(float v) noexcept { if (v != 1.f) { float factor = (1.f - (1.f / v)); @@ -86,7 +86,7 @@ class TPoint constexpr bool operator==(const TPoint& other) const { return other.x == x && other.y == y; } constexpr bool operator!=(const TPoint& other) const { return other.x != x || other.y != y; } - constexpr std::size_t hash() const noexcept { return (7 * 15 + x) * 15 + y; } + [[nodiscard]] constexpr std::size_t hash() const noexcept { return (7 * 15 + x) * 15 + y; } friend std::ostream& operator<<(std::ostream& out, const TPoint& point) { return out << point.x << " " << point.y; diff --git a/src/framework/util/rect.h b/src/framework/util/rect.h index 528fe54cb1..0fc1d51f84 100644 --- a/src/framework/util/rect.h +++ b/src/framework/util/rect.h @@ -111,10 +111,11 @@ class TRect constexpr void moveCenterLeft(const TPoint& p) noexcept { moveLeft(p.x); moveVerticalCenter(p.y); } constexpr void moveCenterRight(const TPoint& p) noexcept { moveRight(p.x); moveVerticalCenter(p.y); } - constexpr TRect translated(T x, T y) const noexcept { return TRect(TPoint(x1 + x, y1 + y), TPoint(x2 + x, y2 + y)); } - constexpr TRect translated(const TPoint& p) const noexcept { return TRect(TPoint(x1 + p.x, y1 + p.y), TPoint(x2 + p.x, y2 + p.y)); } - constexpr TRect expanded(T add) const noexcept { return TRect(TPoint(x1 - add, y1 - add), TPoint(x2 + add, y2 + add)); } - constexpr TRect clamp(const TSize& min, const TSize& max) const noexcept { + [[nodiscard]] constexpr TRect translated(T x, T y) const noexcept { return TRect(TPoint(x1 + x, y1 + y), TPoint(x2 + x, y2 + y)); } + [[nodiscard]] constexpr TRect translated(const TPoint& p) const noexcept { return TRect(TPoint(x1 + p.x, y1 + p.y), TPoint(x2 + p.x, y2 + p.y)); } + [[nodiscard]] constexpr TRect expanded(T add) const noexcept { return TRect(TPoint(x1 - add, y1 - add), TPoint(x2 + add, y2 + add)); } + + [[nodiscard]] constexpr TRect clamp(const TSize& min, const TSize& max) const noexcept { return TRect(x1, y1, std::min(max.width(), std::max(min.width(), width())), std::min(max.height(), std::max(min.height(), height()))); @@ -139,33 +140,33 @@ class TRect y2 = y1 + h; } - constexpr std::size_t hash() const noexcept { + [[nodiscard]] constexpr std::size_t hash() const noexcept { std::size_t h = 37; h = (h * 54059) ^ (x1 * 76963); h = (h * 54059) ^ (y1 * 76963); return h; } - constexpr bool contains(const TPoint& p, bool insideOnly = false) const noexcept { + [[nodiscard]] constexpr bool contains(const TPoint& p, bool insideOnly = false) const noexcept { return (insideOnly ? (p.x > x1 && p.x < x2) : (p.x >= x1 && p.x <= x2)) && (insideOnly ? (p.y > y1 && p.y < y2) : (p.y >= y1 && p.y <= y2)); } - constexpr bool contains(const TRect& r, bool insideOnly = false) const noexcept { + [[nodiscard]] constexpr bool contains(const TRect& r, bool insideOnly = false) const noexcept { return contains(r.topLeft(), insideOnly) && contains(r.bottomRight(), insideOnly); } - constexpr bool intersects(const TRect& r) const noexcept { + [[nodiscard]] constexpr bool intersects(const TRect& r) const noexcept { return !(r.x2 < x1 || r.x1 > x2 || r.y2 < y1 || r.y1 > y2); } - constexpr TRect united(const TRect& r) const noexcept { + [[nodiscard]] constexpr TRect united(const TRect& r) const noexcept { return { std::min(x1, r.x1), std::min(y1, r.y1), std::max(x2, r.x2) - std::min(x1, r.x1) + 1, std::max(y2, r.y2) - std::min(y1, r.y1) + 1 }; } - constexpr TRect intersection(const TRect& r) const noexcept { + [[nodiscard]] constexpr TRect intersection(const TRect& r) const noexcept { if (!intersects(r)) return {}; return { std::max(x1, r.x1), std::max(y1, r.y1), std::min(x2, r.x2) - std::max(x1, r.x1) + 1, diff --git a/src/framework/util/size.h b/src/framework/util/size.h index 522629862b..3d9c6c847e 100644 --- a/src/framework/util/size.h +++ b/src/framework/util/size.h @@ -36,13 +36,13 @@ class TSize constexpr TPoint toPoint() const { return { wd, ht }; } - constexpr bool isNull() const { return wd == 0 && ht == 0; } - constexpr bool isEmpty() const { return wd < 1 || ht < 1; } - constexpr bool isValid() const { return wd >= 0 && ht >= 0; } - constexpr bool isUnset() const { return wd == -1 && ht == -1; } + [[nodiscard]] constexpr bool isNull() const { return wd == 0 && ht == 0; } + [[nodiscard]] constexpr bool isEmpty() const { return wd < 1 || ht < 1; } + [[nodiscard]] constexpr bool isValid() const { return wd >= 0 && ht >= 0; } + [[nodiscard]] constexpr bool isUnset() const { return wd == -1 && ht == -1; } - constexpr T width() const { return wd; } - constexpr T height() const { return ht; } + [[nodiscard]] constexpr T width() const { return wd; } + [[nodiscard]] constexpr T height() const { return ht; } constexpr void resize(T w, T h) { wd = w; ht = h; } constexpr void setWidth(T w) { wd = w; } @@ -108,9 +108,9 @@ class TSize constexpr T smaller() const { return std::min(ht, wd); } constexpr T bigger() const { return std::max(ht, wd); } - constexpr float ratio() const { return static_cast(wd) / ht; } - constexpr T area() const { return wd * ht; } - constexpr T dimension() const { return wd + ht; } + [[nodiscard]] constexpr float ratio() const { return static_cast(wd) / ht; } + [[nodiscard]] constexpr T area() const { return wd * ht; } + [[nodiscard]] constexpr T dimension() const { return wd + ht; } friend std::ostream& operator<<(std::ostream& out, const TSize& size) { out << size.width() << " " << size.height(); diff --git a/src/main.cpp b/src/main.cpp index d347cb1368..8f59c957d8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -125,4 +125,4 @@ extern "C" { } #ifdef ANDROID } -#endif +#endif \ No newline at end of file