From 2169bcd35acb7cb77997fd81a5283a64d5699a7e Mon Sep 17 00:00:00 2001 From: vittorioromeo Date: Tue, 6 Aug 2024 17:17:50 +0200 Subject: [PATCH] adapt to newest sfml --- CMakeLists.txt | 2 +- include/SSVOpenHexagon/Core/HGStatus.hpp | 4 +- include/SSVOpenHexagon/Core/HexagonClient.hpp | 16 ++-- include/SSVOpenHexagon/Core/HexagonGame.hpp | 22 +++--- include/SSVOpenHexagon/Core/HexagonServer.hpp | 12 +-- .../SSVOpenHexagon/Core/LeaderboardCache.hpp | 4 +- include/SSVOpenHexagon/Core/MenuGame.hpp | 8 +- include/SSVOpenHexagon/Core/Replay.hpp | 6 +- include/SSVOpenHexagon/Core/Steam.hpp | 4 +- include/SSVOpenHexagon/Global/Assets.hpp | 6 +- include/SSVOpenHexagon/Global/PCH.hpp | 7 +- include/SSVOpenHexagon/Online/Database.hpp | 10 +-- include/SSVOpenHexagon/Online/Shared.hpp | 4 +- include/SSVOpenHexagon/Online/Sodium.hpp | 6 +- include/SSVOpenHexagon/Utils/Concat.hpp | 8 +- include/SSVOpenHexagon/Utils/String.hpp | 6 +- include/SSVOpenHexagon/Utils/Timeline2.hpp | 4 +- include/SSVOpenHexagon/Utils/Utils.hpp | 4 +- public/sqlite_orm/sqlite_orm.h | 6 +- src/SSVOpenHexagon/Core/Audio.cpp | 2 +- src/SSVOpenHexagon/Core/HGGraphics.cpp | 16 ++-- src/SSVOpenHexagon/Core/HGScripting.cpp | 4 +- src/SSVOpenHexagon/Core/HGUpdate.cpp | 70 +++++++++--------- src/SSVOpenHexagon/Core/HexagonClient.cpp | 56 +++++++------- src/SSVOpenHexagon/Core/HexagonGame.cpp | 38 +++++----- src/SSVOpenHexagon/Core/HexagonServer.cpp | 66 ++++++++--------- src/SSVOpenHexagon/Core/LeaderboardCache.cpp | 6 +- src/SSVOpenHexagon/Core/LuaScripting.cpp | 20 +++-- src/SSVOpenHexagon/Core/MenuGame.cpp | 28 +++---- src/SSVOpenHexagon/Core/Replay.cpp | 16 ++-- src/SSVOpenHexagon/Core/Steam.cpp | 53 +++++++------- src/SSVOpenHexagon/Core/main.cpp | 58 +++++++-------- src/SSVOpenHexagon/Global/Assets.cpp | 20 ++--- src/SSVOpenHexagon/Global/Instantiations.cpp | 8 +- src/SSVOpenHexagon/Online/Database.cpp | 34 ++++----- src/SSVOpenHexagon/Online/Shared.cpp | 73 ++++++++++--------- src/SSVOpenHexagon/Online/Sodium.cpp | 23 +++--- src/SSVOpenHexagon/Utils/Timeline2.cpp | 6 +- src/SSVOpenHexagon/Utils/Utils.cpp | 12 +-- test/Replay.t.cpp | 4 +- test/ReplayExecution.t.cpp | 10 +-- test/ReplayExecutionBenchmark.t.cpp | 10 +-- 42 files changed, 389 insertions(+), 383 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 533a99d15..ba6cc30a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -97,7 +97,7 @@ set(SFML_ENABLE_PCH true) CPMAddPackage( NAME SFML GITHUB_REPOSITORY vittorioromeo/SFML - GIT_TAG dd0cc60de5f07f4180821db9b3f89fbc15cdf03f + GIT_TAG ae249dae3e3de4b1790098a1067c24750921c8ec ) set_target_properties(sfml-system PROPERTIES UNITY_BUILD ON) diff --git a/include/SSVOpenHexagon/Core/HGStatus.hpp b/include/SSVOpenHexagon/Core/HGStatus.hpp index e0e869104..629973349 100644 --- a/include/SSVOpenHexagon/Core/HGStatus.hpp +++ b/include/SSVOpenHexagon/Core/HGStatus.hpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include namespace hg { @@ -78,7 +78,7 @@ struct HexagonGameStatus bool showPlayerTrail{true}; // Shaders - std::array, + std::array, static_cast(RenderStage::Count)> fragmentShaderIds; diff --git a/include/SSVOpenHexagon/Core/HexagonClient.hpp b/include/SSVOpenHexagon/Core/HexagonClient.hpp index fb71cd126..148552013 100644 --- a/include/SSVOpenHexagon/Core/HexagonClient.hpp +++ b/include/SSVOpenHexagon/Core/HexagonClient.hpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include #include #include @@ -84,7 +84,7 @@ class HexagonClient private: Steam::steam_manager& _steamManager; - std::optional _ticketSteamID; + sf::base::Optional _ticketSteamID; const sf::IpAddress _serverIp; const unsigned short _serverPort; @@ -100,13 +100,13 @@ class HexagonClient bool _verbose; const SodiumPSKeys _clientPSKeys; - std::optional _serverPublicKey; - std::optional _clientRTKeys; + sf::base::Optional _serverPublicKey; + sf::base::Optional _clientRTKeys; State _state; - std::optional _loginToken; - std::optional _loginName; + sf::base::Optional _loginToken; + sf::base::Optional _loginName; std::deque _events; @@ -192,10 +192,10 @@ class HexagonClient [[nodiscard]] State getState() const noexcept; [[nodiscard]] bool hasRTKeys() const noexcept; - [[nodiscard]] const std::optional& + [[nodiscard]] const sf::base::Optional& getLoginName() const noexcept; - [[nodiscard]] std::optional pollEvent(); + [[nodiscard]] sf::base::Optional pollEvent(); [[nodiscard]] bool isLevelSupportedByServer( const std::string& levelValidator) const noexcept; diff --git a/include/SSVOpenHexagon/Core/HexagonGame.hpp b/include/SSVOpenHexagon/Core/HexagonGame.hpp index 1faa1a7e7..4a7b26df6 100644 --- a/include/SSVOpenHexagon/Core/HexagonGame.hpp +++ b/include/SSVOpenHexagon/Core/HexagonGame.hpp @@ -42,7 +42,7 @@ #include #include #include -#include +#include #include #include #include @@ -114,7 +114,7 @@ class HexagonGame std::int8_t steamAttempt{1}; HGAssets& assets; - std::optional textUI; + sf::base::Optional textUI; Audio* audio; @@ -151,8 +151,8 @@ class HexagonGame float timeUntilRichPresenceUpdate = 0.f; private: - std::optional backgroundCamera; - std::optional overlayCamera; + sf::base::Optional backgroundCamera; + sf::base::Optional overlayCamera; struct PreShakeCenters { @@ -160,7 +160,7 @@ class HexagonGame sf::Vector2f overlay; }; - std::optional preShakeCenters; + sf::base::Optional preShakeCenters; const sf::Vector2f centerPos{0.f, 0.f}; @@ -219,7 +219,7 @@ class HexagonGame float angle; }; - std::optional swapParticlesSpawnInfo; + sf::base::Optional swapParticlesSpawnInfo; float nextPBParticleSpawn{0.f}; float pbTextGrowth{0.f}; @@ -261,7 +261,7 @@ class HexagonGame explicit ActiveReplay(const replay_file& mReplayFile); }; - std::optional activeReplay; + sf::base::Optional activeReplay; random_number_generator::seed_type lastSeed{}; replay_data lastReplayData{}; @@ -347,11 +347,11 @@ class HexagonGame void initFlashEffect(int r, int g, int b); // Fast-forward - std::optional fastForwardTarget; + sf::base::Optional fastForwardTarget; void fastForwardTo(const double target); // Advance by ticks - std::optional advanceTickCount; + sf::base::Optional advanceTickCount; void advanceByTicks(const int nTicks); // Update methods @@ -501,10 +501,10 @@ class HexagonGame float customScore; }; - [[nodiscard]] std::optional executeGameUntilDeath( + [[nodiscard]] sf::base::Optional executeGameUntilDeath( const int maxProcessingSeconds, const float timescale); - [[nodiscard]] std::optional + [[nodiscard]] sf::base::Optional runReplayUntilDeathAndGetScore(const replay_file& mReplayFile, const int maxProcessingSeconds, const float timescale); diff --git a/include/SSVOpenHexagon/Core/HexagonServer.hpp b/include/SSVOpenHexagon/Core/HexagonServer.hpp index 62089a113..fffba2b32 100644 --- a/include/SSVOpenHexagon/Core/HexagonServer.hpp +++ b/include/SSVOpenHexagon/Core/HexagonServer.hpp @@ -19,7 +19,7 @@ #include #include -#include +#include #include #include #include @@ -69,8 +69,8 @@ class HexagonServer Utils::SCTimePoint _lastActivity; int _consecutiveFailures; bool _mustDisconnect; - std::optional _clientPublicKey; - std::optional _rtKeys; + sf::base::Optional _clientPublicKey; + sf::base::Optional _rtKeys; struct LoginData { @@ -81,7 +81,7 @@ class HexagonServer std::uint64_t _loginToken; }; - std::optional _loginData; + sf::base::Optional _loginData; State _state; @@ -91,7 +91,7 @@ class HexagonServer std::string _levelValidator; }; - std::optional _gameStatus; + sf::base::Optional _gameStatus; explicit ConnectedClient(const Utils::SCTimePoint lastActivity); ~ConnectedClient(); @@ -139,7 +139,7 @@ class HexagonServer [[nodiscard]] bool sendTopScoresAndOwnScore(ConnectedClient& c, const std::string& levelValidator, const std::vector& scores, - const std::optional& ownScore); + const sf::base::Optional& ownScore); [[nodiscard]] bool sendServerStatus(ConnectedClient& c, const ProtocolVersion& protocolVersion, const GameVersion& gameVersion, const std::vector& supportedLevelValidators); diff --git a/include/SSVOpenHexagon/Core/LeaderboardCache.hpp b/include/SSVOpenHexagon/Core/LeaderboardCache.hpp index 4c6cec41a..6976b1faa 100644 --- a/include/SSVOpenHexagon/Core/LeaderboardCache.hpp +++ b/include/SSVOpenHexagon/Core/LeaderboardCache.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include namespace hg { @@ -21,7 +21,7 @@ class LeaderboardCache struct CachedScores { std::vector _scores; - std::optional _ownScore; + sf::base::Optional _ownScore; HRTimePoint _cacheTime; }; diff --git a/include/SSVOpenHexagon/Core/MenuGame.hpp b/include/SSVOpenHexagon/Core/MenuGame.hpp index 17356b32d..612a38f5b 100644 --- a/include/SSVOpenHexagon/Core/MenuGame.hpp +++ b/include/SSVOpenHexagon/Core/MenuGame.hpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include #include #include @@ -272,9 +272,9 @@ class MenuGame bool mousePressed{false}; bool mustFavorite{false}; bool mustPlay{false}; - std::optional mustChangeIndexTo; - std::optional mustChangePackIndexTo; - std::optional mustUseMenuItem; + sf::base::Optional mustChangeIndexTo; + sf::base::Optional mustChangePackIndexTo; + sf::base::Optional mustUseMenuItem; bool mouseCursorVisible{true}; sf::Vector2i lastMouseMovedPosition{}; diff --git a/include/SSVOpenHexagon/Core/Replay.hpp b/include/SSVOpenHexagon/Core/Replay.hpp index 7dd78a49c..af2bdce40 100644 --- a/include/SSVOpenHexagon/Core/Replay.hpp +++ b/include/SSVOpenHexagon/Core/Replay.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include @@ -161,10 +161,10 @@ struct compressed_replay_file [[nodiscard]] bool deserialize_from_packet(sf::Packet& p); }; -[[nodiscard]] std::optional compress_replay_file( +[[nodiscard]] sf::base::Optional compress_replay_file( const replay_file& rf); -[[nodiscard]] std::optional decompress_replay_file( +[[nodiscard]] sf::base::Optional decompress_replay_file( const compressed_replay_file& crf); } // namespace hg diff --git a/include/SSVOpenHexagon/Core/Steam.hpp b/include/SSVOpenHexagon/Core/Steam.hpp index a1a484156..17b11ea5d 100644 --- a/include/SSVOpenHexagon/Core/Steam.hpp +++ b/include/SSVOpenHexagon/Core/Steam.hpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include @@ -62,7 +62,7 @@ class steam_manager [[nodiscard]] bool got_encrypted_app_ticket() const noexcept; - [[nodiscard]] std::optional + [[nodiscard]] sf::base::Optional get_ticket_steam_id() const noexcept; }; diff --git a/include/SSVOpenHexagon/Global/Assets.hpp b/include/SSVOpenHexagon/Global/Assets.hpp index 2bce6d8c0..a91968ea7 100644 --- a/include/SSVOpenHexagon/Global/Assets.hpp +++ b/include/SSVOpenHexagon/Global/Assets.hpp @@ -7,7 +7,7 @@ #include "SSVOpenHexagon/Utils/UniquePtr.hpp" #include -#include +#include #include #include #include @@ -94,9 +94,9 @@ class HGAssets [[nodiscard]] sf::Shader* getShader( const std::string& mPackId, const std::string& mId); - [[nodiscard]] std::optional getShaderId( + [[nodiscard]] sf::base::Optional getShaderId( const std::string& mPackId, const std::string& mId); - [[nodiscard]] std::optional getShaderIdByPath( + [[nodiscard]] sf::base::Optional getShaderIdByPath( const std::string& mShaderPath); [[nodiscard]] sf::Shader* getShaderByShaderId(const std::size_t mShaderId); [[nodiscard]] bool isValidShaderId(const std::size_t mShaderId) const; diff --git a/include/SSVOpenHexagon/Global/PCH.hpp b/include/SSVOpenHexagon/Global/PCH.hpp index f952f8c39..931a30db1 100644 --- a/include/SSVOpenHexagon/Global/PCH.hpp +++ b/include/SSVOpenHexagon/Global/PCH.hpp @@ -47,7 +47,6 @@ #include #include #include -#include #include #include #include @@ -229,9 +228,9 @@ extern template class std::vector; -extern template class std::optional; -extern template class std::optional; -extern template class std::optional; +extern template class sf::base::Optional; +extern template class sf::base::Optional; +extern template class sf::base::Optional; extern template class std::unordered_map; extern template class std::unordered_map; diff --git a/include/SSVOpenHexagon/Online/Database.hpp b/include/SSVOpenHexagon/Online/Database.hpp index b28a10ba1..d96a2a898 100644 --- a/include/SSVOpenHexagon/Online/Database.hpp +++ b/include/SSVOpenHexagon/Online/Database.hpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include // TODO (P2): remove reliance on steam ID for future platforms @@ -25,7 +25,7 @@ void dumpUsers(); [[nodiscard]] bool anyUserWithName(const std::string& name); -[[nodiscard]] std::optional getUserWithSteamIdAndName( +[[nodiscard]] sf::base::Optional getUserWithSteamIdAndName( const std::uint64_t steamId, const std::string& name); void removeAllLoginTokensForUser(const std::uint32_t userId); @@ -35,7 +35,7 @@ void addLoginToken(const LoginToken& loginToken); [[nodiscard]] std::vector getAllUsersWithSteamId( const std::uint64_t steamId); -[[nodiscard]] std::optional getUserWithSteamId( +[[nodiscard]] sf::base::Optional getUserWithSteamId( const std::uint64_t steamId); [[nodiscard]] std::vector getAllStaleLoginTokens(); @@ -49,9 +49,9 @@ void removeAllStaleLoginTokens(); void addScore(const std::string& levelValidator, const std::uint64_t timestamp, const std::uint64_t userSteamId, const double value); -[[nodiscard]] std::optional getScore( +[[nodiscard]] sf::base::Optional getScore( const std::string& levelValidator, const std::uint64_t userSteamId); -[[nodiscard]] std::optional execute(const std::string& query); +[[nodiscard]] sf::base::Optional execute(const std::string& query); } // namespace hg::Database diff --git a/include/SSVOpenHexagon/Online/Shared.hpp b/include/SSVOpenHexagon/Online/Shared.hpp index 604b64880..84b8fd286 100644 --- a/include/SSVOpenHexagon/Online/Shared.hpp +++ b/include/SSVOpenHexagon/Online/Shared.hpp @@ -17,7 +17,7 @@ #include #include -#include +#include #include #include #include @@ -113,7 +113,7 @@ struct STCPDeleteAccountSuccess { }; struct STCPDeleteAccountFailure { std::string error; }; struct STCPTopScores { std::string levelValidator; std::vector scores; }; struct STCPOwnScore { std::string levelValidator; Database::ProcessedScore score; }; -struct STCPTopScoresAndOwnScore { std::string levelValidator; std::vector scores; std::optional ownScore; }; +struct STCPTopScoresAndOwnScore { std::string levelValidator; std::vector scores; sf::base::Optional ownScore; }; struct STCPServerStatus { ProtocolVersion protocolVersion; GameVersion gameVersion; std::vector supportedLevelValidators; }; // clang-format on diff --git a/include/SSVOpenHexagon/Online/Sodium.hpp b/include/SSVOpenHexagon/Online/Sodium.hpp index 3d9819b8c..b87477ac8 100644 --- a/include/SSVOpenHexagon/Online/Sodium.hpp +++ b/include/SSVOpenHexagon/Online/Sodium.hpp @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include @@ -50,11 +50,11 @@ struct SodiumRTKeys [[nodiscard]] SodiumPSKeys generateSodiumPSKeys(); -[[nodiscard]] std::optional calculateServerSessionSodiumRTKeys( +[[nodiscard]] sf::base::Optional calculateServerSessionSodiumRTKeys( const SodiumPSKeys& serverPSKeys, const SodiumPublicKeyArray& clientPublicKey); -[[nodiscard]] std::optional calculateClientSessionSodiumRTKeys( +[[nodiscard]] sf::base::Optional calculateClientSessionSodiumRTKeys( const SodiumPSKeys& clientPSKeys, const SodiumPublicKeyArray& serverPublicKey); diff --git a/include/SSVOpenHexagon/Utils/Concat.hpp b/include/SSVOpenHexagon/Utils/Concat.hpp index 8219b4402..ba864ca2b 100644 --- a/include/SSVOpenHexagon/Utils/Concat.hpp +++ b/include/SSVOpenHexagon/Utils/Concat.hpp @@ -7,9 +7,11 @@ #include #include #include -#include #include +#include +#include + namespace hg::Utils { namespace Impl { @@ -36,8 +38,8 @@ struct IsCharArray : std::true_type template inline constexpr bool AllConvertibleToStringView = - ((std::is_convertible_v || IsCharArray::value || - std::is_same_v) && + ((SFML_BASE_IS_CONVERTIBLE(Ts, std::string_view) || + IsCharArray::value || SFML_BASE_IS_SAME(Ts, char)) && ...); template diff --git a/include/SSVOpenHexagon/Utils/String.hpp b/include/SSVOpenHexagon/Utils/String.hpp index 362820940..1be8e85f6 100644 --- a/include/SSVOpenHexagon/Utils/String.hpp +++ b/include/SSVOpenHexagon/Utils/String.hpp @@ -5,13 +5,13 @@ #pragma once #include -#include +#include namespace hg::Utils { inline void lTrim(std::string& str) { - const auto it = std::find_if( + const auto it = sf::base::findIf( str.begin(), str.end(), [](char ch) { return !std::isspace(ch); }); str.erase(str.begin(), it); @@ -19,7 +19,7 @@ inline void lTrim(std::string& str) inline void rTrim(std::string& str) { - const auto it = std::find_if( + const auto it = sf::base::findIf( str.rbegin(), str.rend(), [](char ch) { return !std::isspace(ch); }); str.erase(it.base(), str.end()); diff --git a/include/SSVOpenHexagon/Utils/Timeline2.hpp b/include/SSVOpenHexagon/Utils/Timeline2.hpp index 85289c31b..f056fd8da 100644 --- a/include/SSVOpenHexagon/Utils/Timeline2.hpp +++ b/include/SSVOpenHexagon/Utils/Timeline2.hpp @@ -8,7 +8,7 @@ #include "SSVOpenHexagon/Utils/TinyVariant.hpp" #include -#include +#include #include #include @@ -90,7 +90,7 @@ class timeline2_runner private: std::size_t _current_idx{0}; - std::optional _wait_start_tp; + sf::base::Optional _wait_start_tp; public: outcome update(timeline2& timeline, const time_point tp); diff --git a/include/SSVOpenHexagon/Utils/Utils.hpp b/include/SSVOpenHexagon/Utils/Utils.hpp index 60e54088b..8beb617d9 100644 --- a/include/SSVOpenHexagon/Utils/Utils.hpp +++ b/include/SSVOpenHexagon/Utils/Utils.hpp @@ -6,7 +6,7 @@ #include #include -#include +#include #include namespace Lua { @@ -71,7 +71,7 @@ T runLuaFunction( Lua::LuaContext& mLua, std::string_view mName, const TArgs&... mArgs); template -std::optional> runLuaFunctionIfExists( +sf::base::Optional> runLuaFunctionIfExists( Lua::LuaContext& mLua, std::string_view mName, const TArgs&... mArgs); const PackData& findDependencyPackDataOrThrow(const HGAssets& assets, diff --git a/public/sqlite_orm/sqlite_orm.h b/public/sqlite_orm/sqlite_orm.h index e5135a2c7..51e1eefb9 100644 --- a/public/sqlite_orm/sqlite_orm.h +++ b/public/sqlite_orm/sqlite_orm.h @@ -508,7 +508,7 @@ namespace sqlite_orm { // #include "cxx_core_features.h" #if SQLITE_ORM_HAS_INCLUDE() -#include +#include #endif #if __cpp_lib_optional >= 201606L @@ -2573,7 +2573,7 @@ namespace sqlite_orm { using unqualified_type = std::remove_cv_t; std::string operator()(const T& t) const { - if(t.has_value()) { + if(t.hasValue()) { return field_printer()(*t); } else { return field_printer{}(std::nullopt); @@ -18333,7 +18333,7 @@ namespace sqlite_orm { object_from_column_builder builder{res.emplace(), stmt}; table.for_each_column(builder); }); - if(!res.has_value()) { + if(!res.hasValue()) { throw std::system_error{orm_error_code::not_found}; } return move(res).value(); diff --git a/src/SSVOpenHexagon/Core/Audio.cpp b/src/SSVOpenHexagon/Core/Audio.cpp index 4b03a7b9c..4f3790d08 100644 --- a/src/SSVOpenHexagon/Core/Audio.cpp +++ b/src/SSVOpenHexagon/Core/Audio.cpp @@ -20,7 +20,7 @@ #include -#include +#include #include namespace hg { diff --git a/src/SSVOpenHexagon/Core/HGGraphics.cpp b/src/SSVOpenHexagon/Core/HGGraphics.cpp index 50b149acd..9d53cbbde 100644 --- a/src/SSVOpenHexagon/Core/HGGraphics.cpp +++ b/src/SSVOpenHexagon/Core/HGGraphics.cpp @@ -64,10 +64,10 @@ void HexagonGame::draw() return sf::RenderStates::Default; } - const std::optional fragmentShaderId = + const sf::base::Optional fragmentShaderId = status.fragmentShaderIds[static_cast(rs)]; - if (!fragmentShaderId.has_value()) + if (!fragmentShaderId.hasValue()) { return sf::RenderStates::Default; } @@ -77,8 +77,8 @@ void HexagonGame::draw() return sf::RenderStates{assets.getShaderByShaderId(*fragmentShaderId)}; }; - SSVOH_ASSERT(backgroundCamera.has_value()); - SSVOH_ASSERT(overlayCamera.has_value()); + SSVOH_ASSERT(backgroundCamera.hasValue()); + SSVOH_ASSERT(overlayCamera.hasValue()); window->clear(sf::Color::Black); @@ -328,7 +328,7 @@ void HexagonGame::drawImguiLuaConsole() return; } - SSVOH_ASSERT(overlayCamera.has_value()); + SSVOH_ASSERT(overlayCamera.hasValue()); sf::RenderWindow& renderWindow = window->getRenderWindow(); window->setView(renderWindow.getDefaultView()); @@ -389,7 +389,7 @@ void HexagonGame::drawLevelInfo(const sf::RenderStates& mStates) { render(levelInfoRectangle, /* texture */ nullptr, mStates); - if (textUI.has_value()) + if (textUI.hasValue()) { render(textUI->levelInfoTextLevel, mStates); render(textUI->levelInfoTextPack, mStates); @@ -425,7 +425,7 @@ void HexagonGame::drawSwapParticles() void HexagonGame::updateText(float mFT) { - if (window == nullptr || !textUI.has_value()) + if (window == nullptr || !textUI.hasValue()) { return; } @@ -610,7 +610,7 @@ void HexagonGame::updateText(float mFT) void HexagonGame::drawText_TimeAndStatus( const sf::Color& offsetColor, const sf::RenderStates& mStates) { - if (!textUI.has_value()) + if (!textUI.hasValue()) { return; } diff --git a/src/SSVOpenHexagon/Core/HGScripting.cpp b/src/SSVOpenHexagon/Core/HGScripting.cpp index b9174af79..601967a15 100644 --- a/src/SSVOpenHexagon/Core/HGScripting.cpp +++ b/src/SSVOpenHexagon/Core/HGScripting.cpp @@ -665,7 +665,7 @@ void HexagonGame::initLua_LevelControl() { // TODO (P2): might break replays if someone uses this to control // game logic - if (backgroundCamera.has_value()) + if (backgroundCamera.hasValue()) { backgroundCamera->setRotation(mValue); } @@ -678,7 +678,7 @@ void HexagonGame::initLua_LevelControl() { // TODO (P2): might break replays if someone uses this to control // game logic - return backgroundCamera.has_value() + return backgroundCamera.hasValue() ? backgroundCamera->getRotation() : 0.f; }) diff --git a/src/SSVOpenHexagon/Core/HGUpdate.cpp b/src/SSVOpenHexagon/Core/HGUpdate.cpp index 32d63e93f..249e8f5da 100644 --- a/src/SSVOpenHexagon/Core/HGUpdate.cpp +++ b/src/SSVOpenHexagon/Core/HGUpdate.cpp @@ -39,7 +39,7 @@ #include #include -#include +#include #include #include @@ -90,7 +90,7 @@ void HexagonGame::update(float mFT, const float timescale) { // ------------------------------------------------------------------------ // Fast-forwarding for level testing - if (fastForwardTarget.has_value()) + if (fastForwardTarget.hasValue()) { const double target = fastForwardTarget.value(); fastForwardTarget.reset(); @@ -109,7 +109,7 @@ void HexagonGame::update(float mFT, const float timescale) // ------------------------------------------------------------------------ // Advance by ticks for level testing - if (advanceTickCount.has_value()) + if (advanceTickCount.hasValue()) { const int nTicks = advanceTickCount.value(); advanceTickCount.reset(); @@ -181,7 +181,7 @@ void HexagonGame::update(float mFT, const float timescale) } else { - SSVOH_ASSERT(activeReplay.has_value()); + SSVOH_ASSERT(activeReplay.hasValue()); if (!status.started) { @@ -247,12 +247,12 @@ void HexagonGame::update(float mFT, const float timescale) if (!status.hasDied) { - const std::optional preventPlayerInput = + const sf::base::Optional preventPlayerInput = runLuaFunctionIfExists( "onInput", mFT, getInputMovement(), getInputFocused(), getInputSwap()); - if (!preventPlayerInput.has_value() || !(*preventPlayerInput)) + if (!preventPlayerInput.hasValue() || !(*preventPlayerInput)) { player.updateInputMovement(getInputMovement(), getPlayerSpeedMult(), getInputFocused(), mFT); @@ -267,20 +267,20 @@ void HexagonGame::update(float mFT, const float timescale) playSoundOverride("swapBlip.ogg"); } - swapParticlesSpawnInfo = + swapParticlesSpawnInfo.emplace( SwapParticleSpawnInfo{.ready{true}, .position{player.getPosition()}, - .angle{player.getPlayerAngle()}}; + .angle{player.getPlayerAngle()}}); } // Create particles after swap if (getLevelStatus().swapEnabled && getInputSwap() && player.isReadyToSwap()) { - swapParticlesSpawnInfo = + swapParticlesSpawnInfo.emplace( SwapParticleSpawnInfo{.ready{false}, .position{player.getPosition()}, - .angle{player.getPlayerAngle()}}; + .angle{player.getPlayerAngle()}}); performPlayerSwap(true /* mPlaySound */); player.resetSwap(getSwapCooldown()); @@ -367,8 +367,8 @@ void HexagonGame::update(float mFT, const float timescale) if (window != nullptr) { - SSVOH_ASSERT(overlayCamera.has_value()); - SSVOH_ASSERT(backgroundCamera.has_value()); + SSVOH_ASSERT(overlayCamera.hasValue()); + SSVOH_ASSERT(backgroundCamera.hasValue()); updateParticles(mFT); @@ -511,7 +511,7 @@ void HexagonGame::start() { status.start(); - if (textUI.has_value()) + if (textUI.hasValue()) { textUI->messageText.setString(""); } @@ -796,7 +796,7 @@ void HexagonGame::refreshPulse() { if (window != nullptr) { - SSVOH_ASSERT(backgroundCamera.has_value()); + SSVOH_ASSERT(backgroundCamera.hasValue()); const float p{ Config::getNoPulse() ? 1.f : (status.pulse / levelStatus.pulseMin)}; @@ -856,21 +856,21 @@ void HexagonGame::updateRotation(float mFT) if (window != nullptr) { - SSVOH_ASSERT(backgroundCamera.has_value()); + SSVOH_ASSERT(backgroundCamera.hasValue()); backgroundCamera->turn(nextRotation); } } void HexagonGame::updateCameraShake(float mFT) { - if (!backgroundCamera.has_value() || !overlayCamera.has_value()) + if (!backgroundCamera.hasValue() || !overlayCamera.hasValue()) { return; } if (status.cameraShake <= 0.f) { - if (preShakeCenters.has_value()) + if (preShakeCenters.hasValue()) { backgroundCamera->setCenter(preShakeCenters->background); overlayCamera->setCenter(preShakeCenters->overlay); @@ -883,15 +883,15 @@ void HexagonGame::updateCameraShake(float mFT) status.cameraShake -= mFT; - if (!preShakeCenters.has_value()) + if (!preShakeCenters.hasValue()) { - preShakeCenters = PreShakeCenters{ - backgroundCamera->getCenter(), overlayCamera->getCenter()}; + preShakeCenters.emplace( + backgroundCamera->getCenter(), overlayCamera->getCenter()); } - SSVOH_ASSERT(backgroundCamera.has_value()); - SSVOH_ASSERT(overlayCamera.has_value()); - SSVOH_ASSERT(preShakeCenters.has_value()); + SSVOH_ASSERT(backgroundCamera.hasValue()); + SSVOH_ASSERT(overlayCamera.hasValue()); + SSVOH_ASSERT(preShakeCenters.hasValue()); const auto makeShakeVec = [this] { @@ -1087,7 +1087,7 @@ void HexagonGame::updateSwapParticles(float mFT) p.sprite.setPosition(p.sprite.getPosition() + p.velocity * mFT); } - if (swapParticlesSpawnInfo.has_value()) + if (swapParticlesSpawnInfo.hasValue()) { if (swapParticlesSpawnInfo->ready == false) { @@ -1343,37 +1343,37 @@ void HexagonGame::postUpdate_ImguiLuaConsole() { const char* item = sItem.c_str(); - const auto color = [&]() -> std::optional + const auto color = [&]() -> sf::base::Optional { if (std::strstr(item, "[error]")) { - return ImVec4(1.0f, 0.4f, 0.4f, 1.0f); + return sf::base::makeOptional(1.0f, 0.4f, 0.4f, 1.0f); } if (std::strstr(item, "[warning]")) { - return ImVec4(1.0f, 0.4f, 1.0f, 1.0f); + return sf::base::makeOptional(1.0f, 0.4f, 1.0f, 1.0f); } if (std::strstr(item, "[lua]")) { - return ImVec4(0.4f, 1.0f, 0.4f, 1.0f); + return sf::base::makeOptional(0.4f, 1.0f, 0.4f, 1.0f); } if (std::strncmp(item, "# ", 2) == 0) { - return ImVec4(1.0f, 0.8f, 0.6f, 1.0f); + return sf::base::makeOptional(1.0f, 0.8f, 0.6f, 1.0f); } if (std::strstr(item, "[?]")) { - return ImVec4(0.4f, 0.4f, 1.0f, 1.0f); + return sf::base::makeOptional(0.4f, 0.4f, 1.0f, 1.0f); } - return std::nullopt; + return sf::base::nullOpt; }(); - if (color.has_value()) + if (color.hasValue()) { ImGui::PushStyleColor(ImGuiCol_Text, *color); } @@ -1416,7 +1416,7 @@ void HexagonGame::postUpdate_ImguiLuaConsole() } } - if (color.has_value()) + if (color.hasValue()) { ImGui::PopStyleColor(); } @@ -1479,7 +1479,7 @@ void HexagonGame::postUpdate_ImguiLuaConsole() ilcCmdLog.emplace_back( Utils::concat("[ff]: fast forwarding to ", seconds, '\n')); - fastForwardTarget = seconds; + fastForwardTarget.emplace(seconds); } catch (const std::invalid_argument&) { @@ -1501,7 +1501,7 @@ void HexagonGame::postUpdate_ImguiLuaConsole() ilcCmdLog.emplace_back(Utils::concat( "[advt]: advancing simulation by ", ticks, " ticks\n")); - advanceTickCount = ticks >= 0 ? ticks : 0; + advanceTickCount.emplace(ticks >= 0 ? ticks : 0); } catch (const std::invalid_argument&) { diff --git a/src/SSVOpenHexagon/Core/HexagonClient.cpp b/src/SSVOpenHexagon/Core/HexagonClient.cpp index aa5d34f05..3bc4c2487 100644 --- a/src/SSVOpenHexagon/Core/HexagonClient.cpp +++ b/src/SSVOpenHexagon/Core/HexagonClient.cpp @@ -74,10 +74,10 @@ template return fail("Never got valid Steam encrypted app ticket"); } - const std::optional ticketSteamId = + const sf::base::Optional ticketSteamId = _steamManager.get_ticket_steam_id(); - if (!ticketSteamId.has_value()) + if (!ticketSteamId.hasValue()) { return fail("No Steam ID received from encrypted app ticket"); } @@ -219,7 +219,7 @@ template return fail(); } - if (!_clientRTKeys.has_value()) + if (!_clientRTKeys.hasValue()) { return fail("Tried to send encrypted message without RT keys"); } @@ -486,7 +486,7 @@ void HexagonClient::disconnect() _socket.setBlocking(true); if ((_state == State::LoggedIn || _state == State::LoggedIn_Ready) && - _ticketSteamID.has_value()) + _ticketSteamID.hasValue()) { (void)sendLogout(*_ticketSteamID); } @@ -547,7 +547,7 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) _errorOss.str(""); const PVServerToClient pv = decodeServerToClientPacket( - _clientRTKeys.has_value() ? &_clientRTKeys->keyReceive : nullptr, + _clientRTKeys.hasValue() ? &_clientRTKeys->keyReceive : nullptr, _errorOss, p); return Utils::match( @@ -578,7 +578,7 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) { SSVOH_CLOG << "Received public key packet from server\n"; - if (_serverPublicKey.has_value()) + if (_serverPublicKey.hasValue()) { SSVOH_CLOG << "Already had public key, replacing\n"; } @@ -587,7 +587,7 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) SSVOH_CLOG << "Did not have public key, setting\n"; } - _serverPublicKey = stcp.key; + _serverPublicKey.emplace(stcp.key); SSVOH_CLOG << "Server public key: '" << sodiumKeyToString(stcp.key) << "'\n"; @@ -596,7 +596,7 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) _clientRTKeys = calculateClientSessionSodiumRTKeys(_clientPSKeys, stcp.key); - if (!_clientRTKeys.has_value()) + if (!_clientRTKeys.hasValue()) { SSVOH_CLOG_ERROR << "Failed calculating RT keys, disconnecting " "from server\n"; @@ -642,7 +642,7 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) SSVOH_CLOG << "Successfully logged into server, token: '" << stcp.loginToken << "'\n"; - if (_loginToken.has_value()) + if (_loginToken.hasValue()) { SSVOH_CLOG << "Already had login token, replacing\n"; } @@ -651,12 +651,12 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) SSVOH_CLOG << "Did not have login token, setting\n"; } - _loginToken = stcp.loginToken; - _loginName = stcp.loginName; + _loginToken.emplace(stcp.loginToken); + _loginName.emplace(stcp.loginName); _state = State::LoggedIn; - SSVOH_ASSERT(_loginToken.has_value()); + SSVOH_ASSERT(_loginToken.hasValue()); return sendRequestServerStatus(_loginToken.value()); }, @@ -734,7 +734,7 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) addEvent(EReceivedTopScores{ .levelValidator = stcp.levelValidator, .scores = stcp.scores}); - if (stcp.ownScore.has_value()) + if (stcp.ownScore.hasValue()) { addEvent( EReceivedOwnScore{.levelValidator = stcp.levelValidator, @@ -770,7 +770,7 @@ bool HexagonClient::receiveDataFromServer(sf::Packet& p) _state = State::LoggedIn_Ready; addEvent(ELoginSuccess{}); - SSVOH_ASSERT(_loginToken.has_value()); + SSVOH_ASSERT(_loginToken.hasValue()); return sendReady(_loginToken.value()); } @@ -829,7 +829,7 @@ bool HexagonClient::tryRegister( return false; } - SSVOH_ASSERT(_ticketSteamID.has_value()); + SSVOH_ASSERT(_ticketSteamID.hasValue()); return sendRegister(_ticketSteamID.value(), name, saltAndHashPwd(password)); } @@ -847,7 +847,7 @@ bool HexagonClient::tryLogin( return false; } - SSVOH_ASSERT(_ticketSteamID.has_value()); + SSVOH_ASSERT(_ticketSteamID.hasValue()); return sendLogin(_ticketSteamID.value(), name, saltAndHashPwd(password)); } @@ -862,7 +862,7 @@ bool HexagonClient::tryLogoutFromServer() _loginToken.reset(); _loginName.reset(); - SSVOH_ASSERT(_ticketSteamID.has_value()); + SSVOH_ASSERT(_ticketSteamID.hasValue()); return sendLogout(_ticketSteamID.value()); } @@ -873,7 +873,7 @@ bool HexagonClient::tryDeleteAccount(const std::string& password) return fail(); } - SSVOH_ASSERT(_ticketSteamID.has_value()); + SSVOH_ASSERT(_ticketSteamID.hasValue()); return sendDeleteAccount(_ticketSteamID.value(), saltAndHashPwd(password)); } @@ -884,7 +884,7 @@ bool HexagonClient::tryRequestTopScores(const std::string& levelValidator) return fail(); } - SSVOH_ASSERT(_loginToken.has_value()); + SSVOH_ASSERT(_loginToken.hasValue()); return sendRequestTopScores(_loginToken.value(), levelValidator); } @@ -904,7 +904,7 @@ bool HexagonClient::trySendCompressedReplay(const std::string& levelValidator, return true; } - SSVOH_ASSERT(_loginToken.has_value()); + SSVOH_ASSERT(_loginToken.hasValue()); return sendCompressedReplay( _loginToken.value(), levelValidator, compressedReplayFile); } @@ -916,7 +916,7 @@ bool HexagonClient::tryRequestOwnScore(const std::string& levelValidator) return fail(); } - SSVOH_ASSERT(_loginToken.has_value()); + SSVOH_ASSERT(_loginToken.hasValue()); return sendRequestOwnScore(_loginToken.value(), levelValidator); } @@ -928,7 +928,7 @@ bool HexagonClient::tryRequestTopScoresAndOwnScore( return fail(); } - SSVOH_ASSERT(_loginToken.has_value()); + SSVOH_ASSERT(_loginToken.hasValue()); return sendRequestTopScoresAndOwnScore(_loginToken.value(), levelValidator); } @@ -939,7 +939,7 @@ bool HexagonClient::trySendStartedGame(const std::string& levelValidator) return fail(); } - SSVOH_ASSERT(_loginToken.has_value()); + SSVOH_ASSERT(_loginToken.hasValue()); return sendStartedGame(_loginToken.value(), levelValidator); } @@ -950,10 +950,10 @@ bool HexagonClient::trySendStartedGame(const std::string& levelValidator) [[nodiscard]] bool HexagonClient::hasRTKeys() const noexcept { - return _clientRTKeys.has_value(); + return _clientRTKeys.hasValue(); } -[[nodiscard]] const std::optional& +[[nodiscard]] const sf::base::Optional& HexagonClient::getLoginName() const noexcept { return _loginName; @@ -976,15 +976,15 @@ void HexagonClient::addEvent(const Event& e) return _socketConnected && (_state == s0 || _state == s1); } -[[nodiscard]] std::optional HexagonClient::pollEvent() +[[nodiscard]] sf::base::Optional HexagonClient::pollEvent() { if (_events.empty()) { - return std::nullopt; + return sf::base::nullOpt; } HG_SCOPE_GUARD({ _events.pop_front(); }); - return {_events.front()}; + return sf::base::makeOptional(_events.front()); } [[nodiscard]] bool HexagonClient::isLevelSupportedByServer( diff --git a/src/SSVOpenHexagon/Core/HexagonGame.cpp b/src/SSVOpenHexagon/Core/HexagonGame.cpp index f6cd4b9c6..4842853f2 100644 --- a/src/SSVOpenHexagon/Core/HexagonGame.cpp +++ b/src/SSVOpenHexagon/Core/HexagonGame.cpp @@ -209,7 +209,7 @@ void HexagonGame::updateLevelInfo() return s; }; - if (textUI.has_value()) + if (textUI.hasValue()) { textUI->levelInfoTextLevel.setFillColor(getColorText()); textUI->levelInfoTextLevel.setCharacterSize( @@ -638,7 +638,7 @@ void HexagonGame::newGame(const std::string& mPackId, const std::string& mId, packId = mPackId; levelId = mId; - if (executeLastReplay && activeReplay.has_value()) + if (executeLastReplay && activeReplay.hasValue()) { firstPlay = activeReplay->replayFile._first_play; } @@ -672,7 +672,7 @@ void HexagonGame::newGame(const std::string& mPackId, const std::string& mId, } else { - if (!activeReplay.has_value()) + if (!activeReplay.hasValue()) { lastPlayedScore = tempReplayScore; @@ -729,7 +729,7 @@ void HexagonGame::newGame(const std::string& mPackId, const std::string& mId, debugPause = false; // Events cleanup - if (textUI.has_value()) + if (textUI.hasValue()) { textUI->messageText.setString(""); textUI->pbText.setString(""); @@ -774,8 +774,8 @@ void HexagonGame::newGame(const std::string& mPackId, const std::string& mId, if (window != nullptr) { - SSVOH_ASSERT(overlayCamera.has_value()); - SSVOH_ASSERT(backgroundCamera.has_value()); + SSVOH_ASSERT(overlayCamera.hasValue()); + SSVOH_ASSERT(backgroundCamera.hasValue()); // Reset zoom overlayCamera->setView( @@ -896,8 +896,8 @@ void HexagonGame::death_shakeCamera() return; } - SSVOH_ASSERT(overlayCamera.has_value()); - SSVOH_ASSERT(backgroundCamera.has_value()); + SSVOH_ASSERT(overlayCamera.hasValue()); + SSVOH_ASSERT(backgroundCamera.hasValue()); overlayCamera->setView( sf::View{{Config::getWidth() / 2.f, Config::getHeight() / 2.f}, @@ -1004,7 +1004,7 @@ void HexagonGame::death_saveScoreIfNeededAndShowPBEffects() SSVOH_ASSERT(r == SaveScoreIfNeededResult::PersonalBest); - if (textUI.has_value()) + if (textUI.hasValue()) { textUI->pbText.setString("NEW PERSONAL BEST!"); } @@ -1085,10 +1085,10 @@ void HexagonGame::death(bool mForce) void HexagonGame::death_sendAndSaveReplay(const replay_file& rf) { - const std::optional crfOpt = + const sf::base::Optional crfOpt = compress_replay_file(rf); - if (!crfOpt.has_value()) + if (!crfOpt.hasValue()) { ssvu::lo("Replay") << "Failed to compress replay, will not save to " "file or send to server\n"; @@ -1170,7 +1170,7 @@ void HexagonGame::death_sendAndSaveReplay(const replay_file& rf) return true; } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional HexagonGame::executeGameUntilDeath( const int maxProcessingSeconds, const float timescale) { @@ -1186,19 +1186,19 @@ HexagonGame::executeGameUntilDeath( if (exceededProcessingTime()) { - return std::nullopt; + return sf::base::nullOpt; } } - return GameExecutionResult{ + return sf::base::makeOptional(GameExecutionResult{ .playedTimeSeconds = status.getPlayedAccumulatedFrametimeInSeconds(), // .pausedTimeSeconds = status.getPausedAccumulatedFrametimeInSeconds(), // .totalTimeSeconds = status.getTotalAccumulatedFrametimeInSeconds(), // .customScore = status.getCustomScore() // - }; + }); } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional HexagonGame::runReplayUntilDeathAndGetScore(const replay_file& mReplayFile, const int maxProcessingSeconds, const float timescale) { @@ -1392,7 +1392,7 @@ void HexagonGame::addMessage( playSoundOverride(levelStatus.beepSound); } - if (textUI.has_value()) + if (textUI.hasValue()) { textUI->messageText.setString(mMessage); } @@ -1402,7 +1402,7 @@ void HexagonGame::addMessage( messageTimeline.append_do( [this] { - if (textUI.has_value()) + if (textUI.hasValue()) { textUI->messageText.setString(""); } @@ -1719,7 +1719,7 @@ void HexagonGame::setSides(unsigned int mSides) [[nodiscard]] bool HexagonGame::inReplay() const noexcept { - return activeReplay.has_value(); + return activeReplay.hasValue(); } [[nodiscard]] bool HexagonGame::mustReplayInput() const noexcept diff --git a/src/SSVOpenHexagon/Core/HexagonServer.cpp b/src/SSVOpenHexagon/Core/HexagonServer.cpp index 74a5f5dc7..c8e853d57 100644 --- a/src/SSVOpenHexagon/Core/HexagonServer.cpp +++ b/src/SSVOpenHexagon/Core/HexagonServer.cpp @@ -39,7 +39,7 @@ #include #include -#include +#include #include #include #include @@ -166,7 +166,7 @@ template { const void* clientAddr = static_cast(&c); - if (!c._rtKeys.has_value()) + if (!c._rtKeys.hasValue()) { return fail( "Tried to send encrypted message without RT keys for client '", @@ -272,7 +272,7 @@ template [[nodiscard]] bool HexagonServer::sendTopScoresAndOwnScore(ConnectedClient& c, const std::string& levelValidator, const std::vector& scores, - const std::optional& ownScore) + const sf::base::Optional& ownScore) { return sendEncrypted(c, // STCPTopScoresAndOwnScore{ @@ -300,7 +300,7 @@ bool HexagonServer::kickAndRemoveClient(ConnectedClient& c) { (void)sendKick(c); - if (c._loginData.has_value()) + if (c._loginData.hasValue()) { Database::removeAllLoginTokensForUser(c._loginData->_userId); } @@ -445,10 +445,10 @@ bool HexagonServer::runIteration_Control() query += splitted[i]; } - const std::optional executeOutcome = + const sf::base::Optional executeOutcome = Database::execute(query); - if(executeOutcome.has_value()) + if(executeOutcome.hasValue()) { SSVOH_SLOG_ERROR << "'db exec' error:\n" << *executeOutcome << '\n'; @@ -638,7 +638,7 @@ void HexagonServer::runIteration_PurgeTokens() ConnectedClient& c = *it; const void* clientAddr = static_cast(&c); - if (!c._loginData.has_value()) + if (!c._loginData.hasValue()) { continue; } @@ -678,7 +678,7 @@ void HexagonServer::runIteration_FlushLogs() { const void* clientAddr = static_cast(&c); - if (!c._loginData.has_value()) + if (!c._loginData.hasValue()) { SSVOH_SLOG << "Client '" << clientAddr << "', is not logged in for " << context << '\n'; @@ -720,7 +720,7 @@ void HexagonServer::runIteration_FlushLogs() return true; }; - if (!c._gameStatus.has_value()) + if (!c._gameStatus.hasValue()) { return discard("no game started"); } @@ -750,11 +750,11 @@ void HexagonServer::runIteration_FlushLogs() constexpr int maxProcessingSeconds = 5; - const std::optional ger = + const sf::base::Optional ger = _hexagonGame.runReplayUntilDeathAndGetScore( rf, maxProcessingSeconds, 1.f /* timescale */); - if (!ger.has_value()) + if (!ger.hasValue()) { return discard( "max processing time exceeded (", maxProcessingSeconds, "s)"); @@ -797,7 +797,7 @@ void HexagonServer::runIteration_FlushLogs() SSVOH_SLOG << "Replay valid, adding to database\n"; - SSVOH_ASSERT(c._loginData.has_value()); + SSVOH_ASSERT(c._loginData.hasValue()); Database::addScore(levelValidator, Utils::nowTimestamp(), c._loginData->_steamId, replayPlayedTime); @@ -875,7 +875,7 @@ void HexagonServer::printCTSPDataVerbose( _errorOss.str(""); const PVClientToServer pv = decodeClientToServerPacket( - c._rtKeys.has_value() ? &c._rtKeys->keyReceive : nullptr, _errorOss, p); + c._rtKeys.hasValue() ? &c._rtKeys->keyReceive : nullptr, _errorOss, p); const auto checkState = [&](const ConnectedClient::State state) { @@ -938,7 +938,7 @@ void HexagonServer::printCTSPDataVerbose( { printCTSPDataVerbose(c, "public key", ctsp); - if (c._clientPublicKey.has_value()) + if (c._clientPublicKey.hasValue()) { SSVOH_SLOG_VERBOSE << "Already had public key, replacing\n"; } @@ -947,7 +947,7 @@ void HexagonServer::printCTSPDataVerbose( SSVOH_SLOG_VERBOSE << "Did not have public key, setting\n"; } - c._clientPublicKey = ctsp.key; + c._clientPublicKey.emplace(ctsp.key); SSVOH_SLOG_VERBOSE << "Client public key: '" << sodiumKeyToString(ctsp.key) << "'\n"; @@ -956,7 +956,7 @@ void HexagonServer::printCTSPDataVerbose( c._rtKeys = calculateServerSessionSodiumRTKeys(_serverPSKeys, ctsp.key); - if (!c._rtKeys.has_value()) + if (!c._rtKeys.hasValue()) { SSVOH_SLOG_ERROR << "Failed calculating RT keys, disconnecting client '" @@ -1062,16 +1062,16 @@ void HexagonServer::printCTSPDataVerbose( return sendFail("No user with name '", name, "' registered"); } - const std::optional user = + const sf::base::Optional user = Database::getUserWithSteamIdAndName(steamId, name); - if (!user.has_value()) + if (!user.hasValue()) { return sendFail("No user matching '", steamId, "' and '", name, "' registered"); } - SSVOH_ASSERT(user.has_value()); + SSVOH_ASSERT(user.hasValue()); if (user->passwordHash != Utils::stringToCharVec(passwordHash)) { @@ -1092,13 +1092,13 @@ void HexagonServer::printCTSPDataVerbose( .token = loginToken // }); - c._loginData = ConnectedClient::LoginData{ + c._loginData.emplace(ConnectedClient::LoginData{ ._userId = user->id, ._steamId = steamId, ._name = name, ._passwordHash = passwordHash, ._loginToken = loginToken // - }; + }); c._state = ConnectedClient::State::LoggedIn; @@ -1116,16 +1116,16 @@ void HexagonServer::printCTSPDataVerbose( return true; } - const std::optional user = + const sf::base::Optional user = Database::getUserWithSteamId(ctsp.steamId); - if (!user.has_value()) + if (!user.hasValue()) { SSVOH_SLOG << "No user with steamId '" << ctsp.steamId << "'\n"; return sendLogoutFailure(c); } - SSVOH_ASSERT(user.has_value()); + SSVOH_ASSERT(user.hasValue()); Database::removeAllLoginTokensForUser(user->id); @@ -1160,15 +1160,15 @@ void HexagonServer::printCTSPDataVerbose( "No user with steamId '", steamId, "' registered"); } - const std::optional user = + const sf::base::Optional user = Database::getUserWithSteamId(ctsp.steamId); - if (!user.has_value()) + if (!user.hasValue()) { return sendFail("No user with steamId '", ctsp.steamId, '\''); } - SSVOH_ASSERT(user.has_value()); + SSVOH_ASSERT(user.hasValue()); if (user->passwordHash != Utils::stringToCharVec(passwordHash)) { @@ -1235,10 +1235,10 @@ void HexagonServer::printCTSPDataVerbose( return true; } - const std::optional ps = + const sf::base::Optional ps = Database::getScore(ctsp.levelValidator, c._loginData->_steamId); - if (!ps.has_value()) + if (!ps.hasValue()) { return true; } @@ -1290,10 +1290,10 @@ void HexagonServer::printCTSPDataVerbose( SSVOH_SLOG << "Client '" << clientAddr << "' started game for level '" << lv << "'\n"; - c._gameStatus = ConnectedClient::GameStatus{ + c._gameStatus.emplace(ConnectedClient::GameStatus{ ._startTP = Utils::SCClock::now(), // ._levelValidator = lv // - }; + }); return true; }, @@ -1309,10 +1309,10 @@ void HexagonServer::printCTSPDataVerbose( const auto& [loginToken, crf] = ctsp; - const std::optional rfOpt = + const sf::base::Optional rfOpt = decompress_replay_file(crf); - if (!rfOpt.has_value()) + if (!rfOpt.hasValue()) { SSVOH_SLOG_ERROR << "Failed to decompress replay received from client '" diff --git a/src/SSVOpenHexagon/Core/LeaderboardCache.cpp b/src/SSVOpenHexagon/Core/LeaderboardCache.cpp index 236662a9e..4ce8237e9 100644 --- a/src/SSVOpenHexagon/Core/LeaderboardCache.cpp +++ b/src/SSVOpenHexagon/Core/LeaderboardCache.cpp @@ -7,7 +7,7 @@ #include "SSVOpenHexagon/Global/Assert.hpp" #include -#include +#include #include #include #include @@ -26,7 +26,7 @@ void LeaderboardCache::receivedOwnScore( const std::string& levelValidator, const Database::ProcessedScore& score) { CachedScores& cs = _levelValidatorToScores[levelValidator]; - cs._ownScore = score; + cs._ownScore.emplace(score); cs._cacheTime = HRClock::now(); } @@ -62,7 +62,7 @@ LeaderboardCache::getScores(const std::string& levelValidator) const SSVOH_ASSERT(hasInformation(levelValidator)); const auto& os = _levelValidatorToScores.at(levelValidator)._ownScore; - return os.has_value() ? &*os : nullptr; + return os.hasValue() ? &*os : nullptr; } [[nodiscard]] bool LeaderboardCache::hasInformation( diff --git a/src/SSVOpenHexagon/Core/LuaScripting.cpp b/src/SSVOpenHexagon/Core/LuaScripting.cpp index 596e815b4..0f02c04e0 100644 --- a/src/SSVOpenHexagon/Core/LuaScripting.cpp +++ b/src/SSVOpenHexagon/Core/LuaScripting.cpp @@ -1244,10 +1244,10 @@ static void initShaders(Lua::LuaContext& lua, HGAssets& assets, const std::string shaderPath = Utils::getDependentShaderFilename( execScriptPackPathContext, fPackPathGetter(), shaderFilename); - const std::optional id = + const sf::base::Optional id = assets.getShaderIdByPath(shaderPath); - if (!id.has_value()) + if (!id.hasValue()) { ssvu::lo("hg::LuaScripting::initShaders") << "`u_getShaderId` failed, no id found for '" @@ -1282,10 +1282,10 @@ static void initShaders(Lua::LuaContext& lua, HGAssets& assets, auto setResult = [&assets, &result](const std::string& shaderPath) { - const std::optional id = + const sf::base::Optional id = assets.getShaderIdByPath(shaderPath); - if (!id.has_value()) + if (!id.hasValue()) { ssvu::lo("hg::LuaScripting::initShaders") << "`u_getDependencyShaderId` failed, no id found for '" @@ -1442,8 +1442,7 @@ static void initShaders(Lua::LuaContext& lua, HGAssets& assets, const auto location = shader.getUniformLocation(name) .value(); // TODO: optimization opportunity - shader.setUniform( - location, sf::Glsl::Vec4{a, b, c, d}); + shader.setUniform(location, sf::Glsl::Vec4{a, b, c, d}); }); }) .arg("shaderId") @@ -1532,8 +1531,7 @@ static void initShaders(Lua::LuaContext& lua, HGAssets& assets, const auto location = shader.getUniformLocation(name) .value(); // TODO: optimization opportunity - shader.setUniform( - location, sf::Glsl::Ivec4{a, b, c, d}); + shader.setUniform(location, sf::Glsl::Ivec4{a, b, c, d}); }); }) .arg("shaderId") @@ -1557,7 +1555,7 @@ static void initShaders(Lua::LuaContext& lua, HGAssets& assets, for (std::size_t i = 0; i < static_cast(RenderStage::Count); ++i) { - ids[i] = std::nullopt; + ids[i] = sf::base::nullOpt; } }) .doc("Reset all active fragment shaders in all render stages."); @@ -1571,7 +1569,7 @@ static void initShaders(Lua::LuaContext& lua, HGAssets& assets, if (checkValidRenderStage( "shdr_resetActiveFragmentShader", renderStage, ids)) { - ids[renderStage] = std::nullopt; + ids[renderStage] = sf::base::nullOpt; } }) .arg("renderStage") @@ -1588,7 +1586,7 @@ static void initShaders(Lua::LuaContext& lua, HGAssets& assets, if (checkValidRenderStage( "shdr_setActiveFragmentShader", renderStage, ids)) { - ids[renderStage] = shaderId; + ids[renderStage].emplace(shaderId); } }) .arg("renderStage") diff --git a/src/SSVOpenHexagon/Core/MenuGame.cpp b/src/SSVOpenHexagon/Core/MenuGame.cpp index a922916a9..37e6fefc0 100644 --- a/src/SSVOpenHexagon/Core/MenuGame.cpp +++ b/src/SSVOpenHexagon/Core/MenuGame.cpp @@ -1128,7 +1128,7 @@ void MenuGame::ignoreInputsAfterMenuExec() // otherwise the user would have to press enter twice to accept in a dialog // box. - setIgnoreAllInputs(mustUseMenuItem.has_value() ? 1 : 2); + setIgnoreAllInputs(mustUseMenuItem.hasValue() ? 1 : 2); } void MenuGame::initMenus() @@ -2551,8 +2551,8 @@ void MenuGame::update(float mFT) SSVOH_ASSERT(ignoreInputs == 1); }; - std::optional hcEvent; - while ((hcEvent = hexagonClient.pollEvent()).has_value()) + sf::base::Optional hcEvent; + while ((hcEvent = hexagonClient.pollEvent()).hasValue()) { Utils::match( *hcEvent, // @@ -2672,7 +2672,7 @@ void MenuGame::update(float mFT) // TODO (P2): cleanup mouse control if ((state == States::SMain || state == States::MOpts || state == States::MOnline || state == States::SLPSelect) && - mustUseMenuItem.has_value()) + mustUseMenuItem.hasValue()) { if (getCurrentMenu() != nullptr) { @@ -2705,7 +2705,7 @@ void MenuGame::update(float mFT) playSelectedLevel(); mustPlay = false; } - else if (mustChangeIndexTo.has_value()) + else if (mustChangeIndexTo.hasValue()) { if (lvlDrawer != nullptr && lvlDrawer->currentIndex != *mustChangeIndexTo) @@ -2716,7 +2716,7 @@ void MenuGame::update(float mFT) mustChangeIndexTo.reset(); } - else if (mustChangePackIndexTo.has_value()) + else if (mustChangePackIndexTo.hasValue()) { if (lvlSlct.packIdx != *mustChangePackIndexTo) { @@ -3749,10 +3749,10 @@ void MenuGame::drawMainMenu( quadHeight + doubleBorder + txtMenuBig.height, false); // TODO (P2): cleanup mouse control - if (mouseOverlap && !mustUseMenuItem.has_value() && + if (mouseOverlap && !mustUseMenuItem.hasValue() && mouseLeftRisingEdge() && items[i]->isEnabled()) { - mustUseMenuItem = i; + mustUseMenuItem.emplace(i); } quadHeight += interline; @@ -5063,9 +5063,9 @@ void MenuGame::drawLevelSelectionRightSide( { mustPlay = true; } - else if (!mustChangeIndexTo.has_value()) + else if (!mustChangeIndexTo.hasValue()) { - mustChangeIndexTo = i; + mustChangeIndexTo.emplace(i); } } @@ -5181,10 +5181,10 @@ void MenuGame::drawLevelSelectionRightSide( mouseOverlapColor(mouseOverlap, menuQuadColor), bodyMins, bodyMaxs); // TODO (P2): cleanup mouse control - if (mouseOverlap && !mustChangePackIndexTo.has_value() && + if (mouseOverlap && !mustChangePackIndexTo.hasValue() && mouseLeftRisingEdge()) { - mustChangePackIndexTo = i; + mustChangePackIndexTo.emplace(i); } window.draw(menuQuads); @@ -6040,7 +6040,7 @@ void MenuGame::drawOnlineStatus() case HexagonClient::State::LoggedIn_Ready: { if (Config::getSaveLastLoginUsername() && - hexagonClient.getLoginName().has_value()) + hexagonClient.getLoginName().hasValue()) { // Save last login username for quicker login next time. @@ -6050,7 +6050,7 @@ void MenuGame::drawOnlineStatus() return { true, "LOGGED IN AS " + - hexagonClient.getLoginName().value_or("UNKNOWN")}; + hexagonClient.getLoginName().valueOr("UNKNOWN")}; } } diff --git a/src/SSVOpenHexagon/Core/Replay.cpp b/src/SSVOpenHexagon/Core/Replay.cpp index 4d9f197b7..6f657a23a 100644 --- a/src/SSVOpenHexagon/Core/Replay.cpp +++ b/src/SSVOpenHexagon/Core/Replay.cpp @@ -501,7 +501,7 @@ static constexpr std::size_t buf_size{2097152}; // 2MB return buf; } -[[nodiscard]] std::optional compress_replay_file( +[[nodiscard]] sf::base::Optional compress_replay_file( const replay_file& rf) { std::byte* buf = get_static_buf(); @@ -509,7 +509,7 @@ static constexpr std::size_t buf_size{2097152}; // 2MB const serialization_result sr = rf.serialize(buf, buf_size); if (!static_cast(sr)) { - return std::nullopt; + return sf::base::nullOpt; } std::byte* compression_buf = get_static_compression_buf(); @@ -524,7 +524,7 @@ static constexpr std::size_t buf_size{2097152}; // 2MB std::cerr << "Failed compression of replay file, error code: '" << rc << "'\n"; - return std::nullopt; + return sf::base::nullOpt; } compressed_replay_file result; @@ -533,10 +533,10 @@ static constexpr std::size_t buf_size{2097152}; // 2MB std::memcpy(static_cast(result._data.data()), static_cast(compression_buf), result._data.size()); - return {std::move(result)}; + return sf::base::makeOptional(std::move(result)); } -[[nodiscard]] std::optional decompress_replay_file( +[[nodiscard]] sf::base::Optional decompress_replay_file( const compressed_replay_file& crf) { std::byte* buf = get_static_buf(); @@ -550,7 +550,7 @@ static constexpr std::size_t buf_size{2097152}; // 2MB std::cerr << "Failed compression of replay file, error code: '" << rc << "'\n"; - return std::nullopt; + return sf::base::nullOpt; } replay_file result; @@ -558,10 +558,10 @@ static constexpr std::size_t buf_size{2097152}; // 2MB const deserialization_result dr = result.deserialize(buf, in_out_dest_len); if (!static_cast(dr)) { - return std::nullopt; + return sf::base::nullOpt; } - return {std::move(result)}; + return sf::base::makeOptional(std::move(result)); } } // namespace hg diff --git a/src/SSVOpenHexagon/Core/Steam.cpp b/src/SSVOpenHexagon/Core/Steam.cpp index 9cd69b9f3..d13b95da0 100644 --- a/src/SSVOpenHexagon/Core/Steam.cpp +++ b/src/SSVOpenHexagon/Core/Steam.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include @@ -32,7 +32,7 @@ namespace hg::Steam { -[[nodiscard]] static std::optional get_user_steam_id() +[[nodiscard]] static sf::base::Optional get_user_steam_id() { // Using C API here because C++ one doesn't work with MinGW. @@ -43,10 +43,11 @@ namespace hg::Steam { ssvu::lo("Steam") << "Attempted to retrieve Steam ID when not logged in\n"; - return std::nullopt; + return sf::base::nullOpt; } - return CSteamID{SteamAPI_ISteamUser_GetSteamID(steam_user)}; + return sf::base::makeOptional( + CSteamID{SteamAPI_ISteamUser_GetSteamID(steam_user)}); } [[nodiscard]] static bool initialize_steamworks() @@ -57,8 +58,9 @@ namespace hg::Steam { { ssvu::lo("Steam") << "Steam API successfully initialized\n"; - if (const std::optional user_steam_id = get_user_steam_id(); - user_steam_id.has_value()) + if (const sf::base::Optional user_steam_id = + get_user_steam_id(); + user_steam_id.hasValue()) { ssvu::lo("Steam") << "User Steam ID: '" << user_steam_id->ConvertToUint64() << "'\n"; @@ -89,7 +91,7 @@ class steam_manager::steam_manager_impl bool _got_stats; bool _got_ticket_response; bool _got_ticket; - std::optional _ticket_steam_id; + sf::base::Optional _ticket_steam_id; std::unordered_set _unlocked_achievements; std::unordered_set _workshop_pack_folders; @@ -149,7 +151,8 @@ class steam_manager::steam_manager_impl bool set_and_store_stat(std::string_view name, int data); [[nodiscard]] bool get_achievement(bool* out, std::string_view name); [[nodiscard]] bool get_stat(int* out, std::string_view name); - [[nodiscard]] std::optional is_achievement_unlocked(const char* name); + [[nodiscard]] sf::base::Optional is_achievement_unlocked( + const char* name); bool update_hardcoded_achievements(); @@ -162,7 +165,7 @@ class steam_manager::steam_manager_impl [[nodiscard]] bool got_encrypted_app_ticket() const noexcept; - [[nodiscard]] std::optional + [[nodiscard]] sf::base::Optional get_ticket_steam_id() const noexcept; }; @@ -447,7 +450,7 @@ bool steam_manager::steam_manager_impl::set_and_store_stat( return false; } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional steam_manager::steam_manager_impl::is_achievement_unlocked(const char* name) { bool res{false}; @@ -455,10 +458,10 @@ steam_manager::steam_manager_impl::is_achievement_unlocked(const char* name) if (!rc) { - return std::nullopt; + return sf::base::nullOpt; } - return res; + return sf::base::makeOptional(res); } bool steam_manager::steam_manager_impl:: @@ -470,7 +473,7 @@ bool steam_manager::steam_manager_impl:: } const auto unlocked = [this](const char* name) -> int - { return is_achievement_unlocked(name).value_or(false) ? 1 : 0; }; + { return is_achievement_unlocked(name).valueOr(false) ? 1 : 0; }; // "Cube Master" { @@ -514,7 +517,7 @@ bool steam_manager::steam_manager_impl:: } const auto unlocked = [this](const char* name) -> int - { return is_achievement_unlocked(name).value_or(false) ? 1 : 0; }; + { return is_achievement_unlocked(name).valueOr(false) ? 1 : 0; }; // "Hypercube Master" { @@ -557,7 +560,7 @@ bool steam_manager::steam_manager_impl::update_hardcoded_achievement_cube_god() } const auto unlocked = [this](const char* name) -> int - { return is_achievement_unlocked(name).value_or(false) ? 1 : 0; }; + { return is_achievement_unlocked(name).valueOr(false) ? 1 : 0; }; // "Cube God" { @@ -600,7 +603,7 @@ bool steam_manager::steam_manager_impl:: } const auto unlocked = [this](const char* name) -> int - { return is_achievement_unlocked(name).value_or(false) ? 1 : 0; }; + { return is_achievement_unlocked(name).valueOr(false) ? 1 : 0; }; // "Hypercube Master" { @@ -782,8 +785,8 @@ void steam_manager::steam_manager_impl::on_encrypted_app_ticket_response( SteamEncryptedAppTicket_GetTicketSteamID( rgubDecrypted, cubDecrypted, &steamIDFromTicket); - if (const std::optional user_steam_id = get_user_steam_id(); - user_steam_id.has_value()) + if (const sf::base::Optional user_steam_id = get_user_steam_id(); + user_steam_id.hasValue()) { if (steamIDFromTicket != *user_steam_id) { @@ -817,14 +820,14 @@ void steam_manager::steam_manager_impl::on_encrypted_app_ticket_response( } _got_ticket = true; - _ticket_steam_id = steamIDFromTicket; + _ticket_steam_id.emplace(steamIDFromTicket); ssvu::lo("Steam") << "GetEncryptedAppTicket succeeded (steamId: '" << steamIDFromTicket.ConvertToUint64() << "')\n"; #else _got_ticket_response = true; _got_ticket = false; - _ticket_steam_id = std::nullopt; + _ticket_steam_id.reset(); #endif } @@ -841,10 +844,10 @@ steam_manager::steam_manager_impl::got_encrypted_app_ticket() const noexcept return _got_ticket; } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional steam_manager::steam_manager_impl::get_ticket_steam_id() const noexcept { - return _ticket_steam_id->ConvertToUint64(); + return sf::base::makeOptional(_ticket_steam_id->ConvertToUint64()); } // ---------------------------------------------------------------------------- @@ -948,7 +951,7 @@ steam_manager::got_encrypted_app_ticket_response() const noexcept return impl().got_encrypted_app_ticket(); } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional steam_manager::get_ticket_steam_id() const noexcept { return impl().get_ticket_steam_id(); @@ -1049,10 +1052,10 @@ steam_manager::got_encrypted_app_ticket_response() const noexcept return false; } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional steam_manager::get_ticket_steam_id() const noexcept { - return std::nullopt; + return sf::base::nullOpt; } } // namespace hg::Steam diff --git a/src/SSVOpenHexagon/Core/main.cpp b/src/SSVOpenHexagon/Core/main.cpp index c10f5179f..dab7120cf 100644 --- a/src/SSVOpenHexagon/Core/main.cpp +++ b/src/SSVOpenHexagon/Core/main.cpp @@ -45,7 +45,7 @@ #include #include #include -#include +#include #include #include @@ -87,8 +87,8 @@ void createFolderIfNonExistant(const std::string& folderName) struct ParsedArgs { std::vector args; - std::optional cliLevelName; - std::optional cliLevelPack; + sf::base::Optional cliLevelName; + sf::base::Optional cliLevelPack; bool printLuaDocs{false}; bool headless{false}; bool server{false}; @@ -104,7 +104,7 @@ struct ParsedArgs if (!std::strcmp(argv[i], "-p") && i + 1 < argc) { ++i; - result.cliLevelPack = argv[i]; + result.cliLevelPack.emplace(argv[i]); continue; } @@ -112,7 +112,7 @@ struct ParsedArgs if (!std::strcmp(argv[i], "-l") && i + 1 < argc) { ++i; - result.cliLevelName = argv[i]; + result.cliLevelName.emplace(argv[i]); continue; } @@ -149,18 +149,18 @@ struct ParsedArgs " - by Vittorio Romeo - https://vittorioromeo.info"); } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional getFirstCompressedReplayFilenameFromArgs(const std::vector& args) { for (const std::string& arg : args) { if (arg.find(".ohr.z") != std::string::npos) { - return arg; + return sf::base::makeOptional(arg); } } - return std::nullopt; + return sf::base::nullOpt; } } // namespace @@ -254,8 +254,8 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) [[nodiscard]] int mainClient(const bool headless, const std::vector& args, - const std::optional& cliLevelName, - const std::optional& cliLevelPack) + const sf::base::Optional& cliLevelName, + const sf::base::Optional& cliLevelPack) { // ------------------------------------------------------------------------ // Steam integration @@ -272,7 +272,7 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) // // ------------------------------------------------------------------------ // Discord integration - std::optional discordManager; + sf::base::Optional discordManager; if (!headless) { @@ -306,7 +306,7 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) // ------------------------------------------------------------------------ // Create the game window sf::GraphicsContext graphicsContext; - std::optional window; + sf::base::Optional window; if (!headless) { @@ -348,7 +348,7 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) // Signal handling: exit gracefully on CTRL-C { - SSVOH_ASSERT(window.has_value()); + SSVOH_ASSERT(window.hasValue()); static ssvs::GameWindow& globalWindow = *window; // TODO (P2): UB @@ -371,7 +371,7 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) // Initialize IMGUI if (!headless) { - SSVOH_ASSERT(window.has_value()); + SSVOH_ASSERT(window.hasValue()); if (!hg::Imgui::initialize(graphicsContext, *window)) { ssvu::lo("::main") << "Failed to initialize ImGui...\n"; @@ -434,10 +434,10 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) hg::HexagonGame hg{ &graphicsContext, &steamManager, // - (discordManager.has_value() ? &*discordManager : nullptr), // + (discordManager.hasValue() ? &*discordManager : nullptr), // assets, // &audio, // - (window.has_value() ? &*window : nullptr), // + (window.hasValue() ? &*window : nullptr), // &hc // }; @@ -445,12 +445,12 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) // // ------------------------------------------------------------------------ // Initialize menu game and link to hexagon game - std::optional mg; + sf::base::Optional mg; if (!headless) { - SSVOH_ASSERT(window.has_value()); - SSVOH_ASSERT(discordManager.has_value()); + SSVOH_ASSERT(window.hasValue()); + SSVOH_ASSERT(discordManager.hasValue()); mg.emplace(graphicsContext, steamManager, *discordManager, assets, audio, *window, hc); @@ -488,12 +488,12 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) // // ------------------------------------------------------------------------ // Load drag & drop replay, if any -- otherwise run game as normal - const std::optional compressedReplayFilename = + const sf::base::Optional compressedReplayFilename = getFirstCompressedReplayFilenameFromArgs(args); if (!headless) { - SSVOH_ASSERT(window.has_value()); + SSVOH_ASSERT(window.hasValue()); const auto gotoMenu = [&] { @@ -504,10 +504,10 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) const auto gotoGameCompressedReplay = [&](const hg::compressed_replay_file& compressedReplayFile) { - std::optional replayFileOpt = + sf::base::Optional replayFileOpt = hg::decompress_replay_file(compressedReplayFile); - if (!replayFileOpt.has_value()) + if (!replayFileOpt.hasValue()) { std::cerr << "Could not decompress replay file\n"; return; @@ -524,9 +524,9 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) window->setGameState(hg.getGame()); }; - if (!compressedReplayFilename.has_value()) + if (!compressedReplayFilename.hasValue()) { - if (cliLevelPack.has_value() && cliLevelName.has_value()) + if (cliLevelPack.hasValue() && cliLevelName.hasValue()) { // Load pack and levels specified via command line args. mg->init(false /* mError */, *cliLevelPack, *cliLevelName); @@ -561,7 +561,7 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) SSVOH_ASSERT(headless); // TODO (P2): code repetition, cleanup - if (!compressedReplayFilename.has_value()) + if (!compressedReplayFilename.hasValue()) { std::cout << "Running in headless mode without replay...?\n"; return 1; @@ -570,10 +570,10 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) if (hg::compressed_replay_file crf; crf.deserialize_from_file(*compressedReplayFilename)) { - std::optional replayFileOpt = + sf::base::Optional replayFileOpt = hg::decompress_replay_file(crf); - if (!replayFileOpt.has_value()) + if (!replayFileOpt.hasValue()) { std::cerr << "Could not decompress replay file\n"; return 1; @@ -609,7 +609,7 @@ getFirstCompressedReplayFilenameFromArgs(const std::vector& args) // Run the game! if (!headless) { - SSVOH_ASSERT(window.has_value()); + SSVOH_ASSERT(window.hasValue()); window->run(graphicsContext); } diff --git a/src/SSVOpenHexagon/Global/Assets.cpp b/src/SSVOpenHexagon/Global/Assets.cpp index 96c1522d4..da1eab5c2 100644 --- a/src/SSVOpenHexagon/Global/Assets.cpp +++ b/src/SSVOpenHexagon/Global/Assets.cpp @@ -173,9 +173,9 @@ class HGAssets::HGAssetsImpl [[nodiscard]] sf::Shader* getShader( const std::string& mPackId, const std::string& mId); - [[nodiscard]] std::optional getShaderId( + [[nodiscard]] sf::base::Optional getShaderId( const std::string& mPackId, const std::string& mId); - [[nodiscard]] std::optional getShaderIdByPath( + [[nodiscard]] sf::base::Optional getShaderIdByPath( const std::string& mShaderPath); [[nodiscard]] sf::Shader* getShaderByShaderId(const std::size_t mShaderId); [[nodiscard]] bool isValidShaderId(const std::size_t mShaderId) const; @@ -1128,7 +1128,7 @@ void HGAssets::HGAssetsImpl::saveAllProfiles() return it->second.shader.get(); } -[[nodiscard]] std::optional HGAssets::HGAssetsImpl::getShaderId( +[[nodiscard]] sf::base::Optional HGAssets::HGAssetsImpl::getShaderId( const std::string& mPackId, const std::string& mId) { const std::string& assetId = concatIntoBuf(mPackId, '_', mId); @@ -1137,13 +1137,13 @@ void HGAssets::HGAssetsImpl::saveAllProfiles() if (it == shaders.end()) { ssvu::lo("getShaderId") << "Asset '" << assetId << "' not found\n"; - return std::nullopt; + return sf::base::nullOpt; } - return it->second.id; + return sf::base::makeOptional(it->second.id); } -[[nodiscard]] std::optional +[[nodiscard]] sf::base::Optional HGAssets::HGAssetsImpl::getShaderIdByPath(const std::string& mShaderPath) { const auto it = shadersPathToId.find(mShaderPath); @@ -1152,10 +1152,10 @@ HGAssets::HGAssetsImpl::getShaderIdByPath(const std::string& mShaderPath) ssvu::lo("getShaderIdByPath") << "Shader with path '" << mShaderPath << "' not found, couldn't get id\n"; - return std::nullopt; + return sf::base::nullOpt; } - return it->second; + return sf::base::makeOptional(it->second); } [[nodiscard]] sf::Shader* HGAssets::HGAssetsImpl::getShaderByShaderId( @@ -1726,13 +1726,13 @@ sf::Shader* HGAssets::getShader( return _impl->getShader(mPackId, mId); } -std::optional HGAssets::getShaderId( +sf::base::Optional HGAssets::getShaderId( const std::string& mPackId, const std::string& mId) { return _impl->getShaderId(mPackId, mId); } -std::optional HGAssets::getShaderIdByPath( +sf::base::Optional HGAssets::getShaderIdByPath( const std::string& mShaderPath) { return _impl->getShaderIdByPath(mShaderPath); diff --git a/src/SSVOpenHexagon/Global/Instantiations.cpp b/src/SSVOpenHexagon/Global/Instantiations.cpp index ce3d0cc6b..4d00575b9 100644 --- a/src/SSVOpenHexagon/Global/Instantiations.cpp +++ b/src/SSVOpenHexagon/Global/Instantiations.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include #include #include @@ -9,9 +9,9 @@ template class std::vector; -template class std::optional; -template class std::optional; -template class std::optional; +template class sf::base::Optional; +template class sf::base::Optional; +template class sf::base::Optional; template class std::unordered_map; template class std::unordered_map; diff --git a/src/SSVOpenHexagon/Online/Database.cpp b/src/SSVOpenHexagon/Online/Database.cpp index 2e4ee03da..eb13ec4b1 100644 --- a/src/SSVOpenHexagon/Online/Database.cpp +++ b/src/SSVOpenHexagon/Online/Database.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include static auto& dlog(const char* funcName) @@ -125,7 +125,7 @@ void dumpUsers() return !query.empty(); } -[[nodiscard]] std::optional getUserWithSteamIdAndName( +[[nodiscard]] sf::base::Optional getUserWithSteamIdAndName( const std::uint64_t steamId, const std::string& name) { using namespace sqlite_orm; @@ -135,7 +135,7 @@ void dumpUsers() if (query.empty()) { - return std::nullopt; + return sf::base::nullOpt; } if (query.size() > 1) @@ -144,11 +144,11 @@ void dumpUsers() << "Database integrity error, multiple users with same steamId '" << steamId << "' and name '" << name << "'\n"; - return std::nullopt; + return sf::base::nullOpt; } SSVOH_ASSERT(query.size() == 1); - return {query[0]}; + return sf::base::makeOptional(query[0]); } void removeAllLoginTokensForUser(const std::uint32_t userId) @@ -178,14 +178,14 @@ void addLoginToken(const LoginToken& loginToken) return query; } -[[nodiscard]] std::optional getUserWithSteamId( +[[nodiscard]] sf::base::Optional getUserWithSteamId( const std::uint64_t steamId) { const auto query = getAllUsersWithSteamId(steamId); if (query.empty()) { - return std::nullopt; + return sf::base::nullOpt; } if (query.size() > 1) @@ -194,11 +194,11 @@ void addLoginToken(const LoginToken& loginToken) << "Database integrity error, multiple users with same steamId '" << steamId << "'\n"; - return std::nullopt; + return sf::base::nullOpt; } SSVOH_ASSERT(query.size() == 1); - return {query[0]}; + return sf::base::makeOptional(query[0]); } constexpr int tokenValiditySeconds = 3600; @@ -321,7 +321,7 @@ void addScore(const std::string& levelValidator, const std::uint64_t timestamp, << Impl::getStorage().dump(score) << '\n'; } -[[nodiscard]] std::optional getScore( +[[nodiscard]] sf::base::Optional getScore( const std::string& levelValidator, const std::uint64_t userSteamId) { using namespace sqlite_orm; @@ -335,7 +335,7 @@ void addScore(const std::string& levelValidator, const std::uint64_t timestamp, if (query.empty()) { - return std::nullopt; + return sf::base::nullOpt; } std::uint32_t index = 0; @@ -343,21 +343,21 @@ void addScore(const std::string& levelValidator, const std::uint64_t timestamp, { if (std::get<3>(row) == userSteamId) { - return {ProcessedScore{ + return sf::base::makeOptional(ProcessedScore{ .position = index, // .userName = std::get<0>(row), // .scoreTimestamp = std::get<1>(row), // .scoreValue = std::get<2>(row), // - }}; + }); } ++index; } - return std::nullopt; + return sf::base::nullOpt; } -[[nodiscard]] std::optional execute(const std::string& query) +[[nodiscard]] sf::base::Optional execute(const std::string& query) { const auto callback = [](void* a_param, int argc, char** argv, char** column) -> int @@ -382,10 +382,10 @@ void addScore(const std::string& levelValidator, const std::uint64_t timestamp, if (error != nullptr) { HG_SCOPE_GUARD({ sqlite3_free(error); }); - return {error}; + return sf::base::makeOptional(error); } - return std::nullopt; + return sf::base::nullOpt; } } // namespace hg::Database diff --git a/src/SSVOpenHexagon/Online/Shared.cpp b/src/SSVOpenHexagon/Online/Shared.cpp index d351c9ce9..3d75fe544 100644 --- a/src/SSVOpenHexagon/Online/Shared.cpp +++ b/src/SSVOpenHexagon/Online/Shared.cpp @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include namespace hg { @@ -232,9 +232,9 @@ struct Extractor> }; template -struct Extractor> +struct Extractor> { - using Type = std::optional; + using Type = sf::base::Optional; [[nodiscard]] static bool doExtractInto( Type& result, std::ostringstream& errorOss, sf::Packet& p) @@ -345,17 +345,17 @@ template } template -[[nodiscard]] std::optional extract( +[[nodiscard]] sf::base::Optional extract( std::ostringstream& errorOss, sf::Packet& p) { T temp; if (!extractInto(temp, errorOss, p)) { - return std::nullopt; + return sf::base::nullOpt; } - return {std::move(temp)}; + return sf::base::makeOptional(std::move(temp)); } template @@ -429,16 +429,16 @@ class AdvancedMatcher } template - [[nodiscard]] std::optional extractOrPrintError(const char* name) + [[nodiscard]] sf::base::Optional extractOrPrintError(const char* name) { T temp; if (!extractIntoOrPrintError(name, temp)) { - return std::nullopt; + return sf::base::nullOpt; } - return {std::move(temp)}; + return sf::base::makeOptional(std::move(temp)); } template @@ -461,7 +461,7 @@ template template [[nodiscard]] auto makeExtractor(std::ostringstream& errorOss, sf::Packet& p) { - return [&](const char* name) -> std::optional + return [&](const char* name) -> sf::base::Optional { return AdvancedMatcher{errorOss, p}.extractOrPrintError(name); }; } @@ -485,18 +485,18 @@ template m.skipOrPrintError("micro version"); } -[[nodiscard]] std::optional extractPacketType( +[[nodiscard]] sf::base::Optional extractPacketType( std::ostringstream& errorOss, sf::Packet& p) { - const std::optional extracted = + const sf::base::Optional extracted = makeExtractor(errorOss, p)("packet type"); - if (!extracted.has_value()) + if (!extracted.hasValue()) { - return std::nullopt; + return sf::base::nullOpt; } - return {static_cast(*extracted)}; + return sf::base::makeOptional(static_cast(*extracted)); } template @@ -577,11 +577,12 @@ void encodeField(sf::Packet& p, const TData& data, const std::vector& vec) } template -void encodeField(sf::Packet& p, const TData& data, const std::optional& opt) +void encodeField( + sf::Packet& p, const TData& data, const sf::base::Optional& opt) { - encodeField(p, data, opt.has_value()); + encodeField(p, data, opt.hasValue()); - if (opt.has_value()) + if (opt.hasValue()) { encodeField(p, data, *opt); } @@ -771,24 +772,24 @@ VRM_PP_FOREACH_REVERSE(INSTANTIATE_MAKE_CTS_ENCRYPTED, VRM_PP_EMPTY(), } \ while (false) -#define INJECT_COMMON_PACKET_HANDLING_CODE(function) \ - const std::optional pt = extractPacketType(errorOss, p); \ - \ - if (!pt.has_value()) \ - { \ - return {PInvalid{.error = errorOss.str()}}; \ - } \ - \ - if (*pt == getPacketType()) \ - { \ - if (!decodeEncryptedPacket(keyReceive, errorOss, p)) \ - { \ - return {PInvalid{.error = errorOss.str()}}; \ - } \ - \ - return function(keyReceive, errorOss, getStaticPacketBuffer()); \ - } \ - \ +#define INJECT_COMMON_PACKET_HANDLING_CODE(function) \ + const sf::base::Optional pt = extractPacketType(errorOss, p); \ + \ + if (!pt.hasValue()) \ + { \ + return {PInvalid{.error = errorOss.str()}}; \ + } \ + \ + if (*pt == getPacketType()) \ + { \ + if (!decodeEncryptedPacket(keyReceive, errorOss, p)) \ + { \ + return {PInvalid{.error = errorOss.str()}}; \ + } \ + \ + return function(keyReceive, errorOss, getStaticPacketBuffer()); \ + } \ + \ const auto extractAllMembers = makeExtractAllMembers(errorOss, p) diff --git a/src/SSVOpenHexagon/Online/Sodium.cpp b/src/SSVOpenHexagon/Online/Sodium.cpp index cf96e5309..f0d37ffeb 100644 --- a/src/SSVOpenHexagon/Online/Sodium.cpp +++ b/src/SSVOpenHexagon/Online/Sodium.cpp @@ -6,8 +6,11 @@ #include -#include -#include +#include + +#include +#include +#include namespace hg { @@ -25,8 +28,8 @@ namespace hg { return result; } -[[nodiscard]] std::optional calculateServerSessionSodiumRTKeys( - const SodiumPSKeys& serverPSKeys, +[[nodiscard]] sf::base::Optional +calculateServerSessionSodiumRTKeys(const SodiumPSKeys& serverPSKeys, const SodiumPublicKeyArray& clientPublicKey) { SodiumRTKeys result; @@ -35,14 +38,14 @@ namespace hg { result.keyTransmit.data(), serverPSKeys.keyPublic.data(), serverPSKeys.keySecret.data(), clientPublicKey.data()) != 0) { - return std::nullopt; + return sf::base::nullOpt; } - return result; + return sf::base::makeOptional(result); } -[[nodiscard]] std::optional calculateClientSessionSodiumRTKeys( - const SodiumPSKeys& clientPSKeys, +[[nodiscard]] sf::base::Optional +calculateClientSessionSodiumRTKeys(const SodiumPSKeys& clientPSKeys, const SodiumPublicKeyArray& serverPublicKey) { SodiumRTKeys result; @@ -51,10 +54,10 @@ namespace hg { result.keyTransmit.data(), clientPSKeys.keyPublic.data(), clientPSKeys.keySecret.data(), serverPublicKey.data()) != 0) { - return std::nullopt; + return sf::base::nullOpt; } - return result; + return sf::base::makeOptional(result); } // ---------------------------------------------------------------------------- diff --git a/src/SSVOpenHexagon/Utils/Timeline2.cpp b/src/SSVOpenHexagon/Utils/Timeline2.cpp index 74f89babd..675ac8997 100644 --- a/src/SSVOpenHexagon/Utils/Timeline2.cpp +++ b/src/SSVOpenHexagon/Utils/Timeline2.cpp @@ -8,7 +8,7 @@ #include "SSVOpenHexagon/Utils/TinyVariant.hpp" #include -#include +#include namespace hg::Utils { @@ -74,10 +74,10 @@ timeline2_runner::outcome timeline2_runner::update( }, [&](timeline2::action_wait_for& x) { - if (!_wait_start_tp.has_value()) + if (!_wait_start_tp.hasValue()) { // Just started waiting. - _wait_start_tp = tp; + _wait_start_tp.emplace(tp); } const auto elapsed = tp - _wait_start_tp.value(); diff --git a/src/SSVOpenHexagon/Utils/Utils.cpp b/src/SSVOpenHexagon/Utils/Utils.cpp index ab6046c24..110e43dd6 100644 --- a/src/SSVOpenHexagon/Utils/Utils.cpp +++ b/src/SSVOpenHexagon/Utils/Utils.cpp @@ -253,10 +253,10 @@ T runLuaFunction( } template -std::optional> runLuaFunctionIfExists( +sf::base::Optional> runLuaFunctionIfExists( Lua::LuaContext& mLua, std::string_view mName, const TArgs&... mArgs) { - using Ret = std::optional>; + using Ret = sf::base::Optional>; if (!mLua.doesVariableExist(mName)) { @@ -276,18 +276,18 @@ std::optional> runLuaFunctionIfExists( template void runLuaFunction(Lua::LuaContext&, std::string_view); -template std::optional> runLuaFunctionIfExists( +template sf::base::Optional> runLuaFunctionIfExists( Lua::LuaContext&, std::string_view); -template std::optional> +template sf::base::Optional> runLuaFunctionIfExists( Lua::LuaContext&, std::string_view, const float&); -template std::optional> +template sf::base::Optional> runLuaFunctionIfExists( Lua::LuaContext&, std::string_view, const float&, const float&); -template std::optional> +template sf::base::Optional> runLuaFunctionIfExists(Lua::LuaContext&, std::string_view, const float&, const int&, const bool&, const bool&); diff --git a/test/Replay.t.cpp b/test/Replay.t.cpp index 57e058538..e0a6da99d 100644 --- a/test/Replay.t.cpp +++ b/test/Replay.t.cpp @@ -185,7 +185,7 @@ void test_impl_packet_serialization(hg::replay_file& rf) void test_impl_file_compressed_serialization(hg::replay_file& rf) { - std::optional crf = + sf::base::Optional crf = hg::compress_replay_file(rf); TEST_ASSERT(crf.value().serialize_to_file("test.ohr")); @@ -193,7 +193,7 @@ void test_impl_file_compressed_serialization(hg::replay_file& rf) hg::compressed_replay_file crf_out; TEST_ASSERT(crf_out.deserialize_from_file("test.ohr")); - std::optional rf_out = hg::decompress_replay_file(crf_out); + sf::base::Optional rf_out = hg::decompress_replay_file(crf_out); TEST_ASSERT_NS_EQ(rf_out.value(), rf); } diff --git a/test/ReplayExecution.t.cpp b/test/ReplayExecution.t.cpp index 39a4c1bb8..db0324262 100644 --- a/test/ReplayExecution.t.cpp +++ b/test/ReplayExecution.t.cpp @@ -15,7 +15,7 @@ #include "TestUtils.hpp" #include -#include +#include #include int main() @@ -66,7 +66,7 @@ try hg.alwaysSpinRight = true; } - std::optional rf; + sf::base::Optional rf; hg.onDeathReplayCreated = [&](const hg::replay_file& newRf) { rf.emplace(newRf); }; @@ -82,9 +82,9 @@ try .value() .playedTimeSeconds; - TEST_ASSERT(rf.has_value()); + TEST_ASSERT(rf.hasValue()); - std::optional score2; + sf::base::Optional score2; if (differentHG) { hg::HexagonGame hg2{ @@ -106,7 +106,7 @@ try rf.value(), 1 /* maxProcessingSeconds */, 1.f /* timescale */); } - TEST_ASSERT(score2.has_value()); + TEST_ASSERT(score2.hasValue()); const double replayPlayedTimeSeconds = score2.value().playedTimeSeconds; std::cerr << score << " == " << replayPlayedTimeSeconds << std::endl; diff --git a/test/ReplayExecutionBenchmark.t.cpp b/test/ReplayExecutionBenchmark.t.cpp index 53baafdfd..ecc1ff3a7 100644 --- a/test/ReplayExecutionBenchmark.t.cpp +++ b/test/ReplayExecutionBenchmark.t.cpp @@ -13,7 +13,7 @@ #include "TestUtils.hpp" #include -#include +#include #include #include @@ -64,7 +64,7 @@ try hg.alwaysSpinRight = true; } - std::optional rf; + sf::base::Optional rf; hg.onDeathReplayCreated = [&](const hg::replay_file& newRf) { rf.emplace(newRf); }; @@ -80,9 +80,9 @@ try .value() .playedTimeSeconds; - TEST_ASSERT(rf.has_value()); + TEST_ASSERT(rf.hasValue()); - std::optional score2; + sf::base::Optional score2; if (differentHG) { hg::HexagonGame hg2{ @@ -104,7 +104,7 @@ try rf.value(), 1 /* maxProcessingSeconds */, 1.f /* timescale */); } - TEST_ASSERT(score2.has_value()); + TEST_ASSERT(score2.hasValue()); const double replayPlayedTimeSeconds = score2.value().playedTimeSeconds; // std::cerr << score << " == " << replayPlayedTimeSeconds << std::endl;