From d0fbd68055e3f4a796330cc8acc6c0954b5327ff Mon Sep 17 00:00:00 2001 From: untodesu Date: Thu, 11 Sep 2025 15:48:53 +0500 Subject: Run clang-format across the project --- core/config/boolean.cc | 86 +- core/config/boolean.hh | 50 +- core/config/ivalue.hh | 22 +- core/config/number.hh | 260 ++-- core/config/string.cc | 36 +- core/config/string.hh | 62 +- core/io/buffer.cc | 690 +++++------ core/io/buffer.hh | 176 +-- core/io/cmdline.cc | 190 +-- core/io/cmdline.hh | 22 +- core/io/config_map.cc | 272 ++--- core/io/config_map.hh | 58 +- core/math/aabb.cc | 118 +- core/math/aabb.hh | 56 +- core/math/angles.hh | 206 ++-- core/math/concepts.hh | 22 +- core/math/constexpr.hh | 396 +++--- core/math/crc64.cc | 142 +-- core/math/crc64.hh | 16 +- core/math/randomizer.hh | 112 +- core/math/vectors.hh | 86 +- core/pch.hh | 98 +- core/resource/image.cc | 162 +-- core/resource/image.hh | 22 +- core/resource/resource.cc | 258 ++-- core/resource/resource.hh | 106 +- core/threading.cc | 256 ++-- core/threading.hh | 92 +- core/utils/epoch.cc | 78 +- core/utils/epoch.hh | 30 +- core/utils/physfs.cc | 152 +-- core/utils/physfs.hh | 28 +- core/utils/string.cc | 114 +- core/utils/string.hh | 34 +- core/version.hh | 28 +- game/client/config/gamepad_axis.cc | 230 ++-- game/client/config/gamepad_axis.hh | 76 +- game/client/config/gamepad_button.cc | 180 +-- game/client/config/gamepad_button.hh | 56 +- game/client/config/keybind.cc | 404 +++---- game/client/config/keybind.hh | 50 +- game/client/const.hh | 46 +- game/client/entity/camera.cc | 228 ++-- game/client/entity/camera.hh | 62 +- game/client/entity/factory.cc | 60 +- game/client/entity/factory.hh | 22 +- game/client/entity/interpolation.cc | 126 +- game/client/entity/interpolation.hh | 12 +- game/client/entity/listener.cc | 84 +- game/client/entity/listener.hh | 12 +- game/client/entity/player_look.cc | 310 ++--- game/client/entity/player_look.hh | 14 +- game/client/entity/player_move.cc | 596 ++++----- game/client/entity/player_move.hh | 30 +- game/client/entity/sound_emitter.cc | 126 +- game/client/entity/sound_emitter.hh | 40 +- game/client/experiments.cc | 162 +-- game/client/experiments.hh | 32 +- game/client/game.cc | 1386 ++++++++++----------- game/client/game.hh | 70 +- game/client/globals.cc | 94 +- game/client/globals.hh | 142 +-- game/client/gui/background.cc | 78 +- game/client/gui/background.hh | 16 +- game/client/gui/bother.cc | 326 ++--- game/client/gui/bother.hh | 44 +- game/client/gui/chat.cc | 546 ++++----- game/client/gui/chat.hh | 34 +- game/client/gui/crosshair.cc | 86 +- game/client/gui/crosshair.hh | 16 +- game/client/gui/direct_connection.cc | 290 ++--- game/client/gui/direct_connection.hh | 14 +- game/client/gui/gui_screen.hh | 20 +- game/client/gui/hotbar.cc | 366 +++--- game/client/gui/hotbar.hh | 54 +- game/client/gui/imdraw_ext.cc | 68 +- game/client/gui/imdraw_ext.hh | 34 +- game/client/gui/language.cc | 402 +++---- game/client/gui/language.hh | 84 +- game/client/gui/main_menu.cc | 344 +++--- game/client/gui/main_menu.hh | 16 +- game/client/gui/message_box.cc | 190 +-- game/client/gui/message_box.hh | 40 +- game/client/gui/metrics.cc | 206 ++-- game/client/gui/metrics.hh | 14 +- game/client/gui/play_menu.cc | 1128 ++++++++--------- game/client/gui/play_menu.hh | 18 +- game/client/gui/progress_bar.cc | 222 ++-- game/client/gui/progress_bar.hh | 38 +- game/client/gui/scoreboard.cc | 206 ++-- game/client/gui/scoreboard.hh | 14 +- game/client/gui/settings.cc | 2138 ++++++++++++++++----------------- game/client/gui/settings.hh | 180 +-- game/client/gui/splash.cc | 356 +++--- game/client/gui/splash.hh | 16 +- game/client/gui/status_lines.cc | 168 +-- game/client/gui/status_lines.hh | 42 +- game/client/gui/window_title.cc | 46 +- game/client/gui/window_title.hh | 12 +- game/client/io/gamepad.cc | 366 +++--- game/client/io/gamepad.hh | 100 +- game/client/io/glfw.hh | 80 +- game/client/main.cc | 898 +++++++------- game/client/pch.hh | 56 +- game/client/program.cc | 448 +++---- game/client/program.hh | 68 +- game/client/receive.cc | 384 +++--- game/client/receive.hh | 12 +- game/client/resource/sound_effect.cc | 180 +-- game/client/resource/sound_effect.hh | 16 +- game/client/resource/texture_gui.cc | 166 +-- game/client/resource/texture_gui.hh | 30 +- game/client/screenshot.cc | 172 +-- game/client/screenshot.hh | 14 +- game/client/session.cc | 614 +++++----- game/client/session.hh | 54 +- game/client/sound/sound.cc | 422 +++---- game/client/sound/sound.hh | 86 +- game/client/toggles.cc | 314 ++--- game/client/toggles.hh | 70 +- game/client/world/chunk_mesher.cc | 968 +++++++-------- game/client/world/chunk_mesher.hh | 36 +- game/client/world/chunk_quad.hh | 82 +- game/client/world/chunk_renderer.cc | 408 +++---- game/client/world/chunk_renderer.hh | 16 +- game/client/world/chunk_vbo.hh | 44 +- game/client/world/chunk_visibility.cc | 180 +-- game/client/world/chunk_visibility.hh | 12 +- game/client/world/outline.cc | 300 ++--- game/client/world/outline.hh | 32 +- game/client/world/player_target.cc | 138 +-- game/client/world/player_target.hh | 36 +- game/client/world/skybox.cc | 22 +- game/client/world/skybox.hh | 22 +- game/client/world/voxel_anims.cc | 66 +- game/client/world/voxel_anims.hh | 26 +- game/client/world/voxel_atlas.cc | 370 +++--- game/client/world/voxel_atlas.hh | 56 +- game/client/world/voxel_sounds.cc | 172 +-- game/client/world/voxel_sounds.hh | 38 +- game/server/chat.cc | 110 +- game/server/chat.hh | 24 +- game/server/game.cc | 312 ++--- game/server/game.hh | 50 +- game/server/globals.cc | 36 +- game/server/globals.hh | 54 +- game/server/main.cc | 216 ++-- game/server/pch.hh | 6 +- game/server/receive.cc | 348 +++--- game/server/receive.hh | 12 +- game/server/sessions.cc | 862 ++++++------- game/server/sessions.hh | 110 +- game/server/status.cc | 52 +- game/server/status.hh | 12 +- game/server/whitelist.cc | 202 ++-- game/server/whitelist.hh | 52 +- game/server/world/inhabited.hh | 12 +- game/server/world/overworld.cc | 766 ++++++------ game/server/world/overworld.hh | 136 +-- game/server/world/universe.cc | 442 +++---- game/server/world/universe.hh | 50 +- game/server/world/unloader.cc | 156 +-- game/server/world/unloader.hh | 26 +- game/server/world/worldgen.cc | 302 ++--- game/server/world/worldgen.hh | 42 +- game/shared/const.hh | 86 +- game/shared/coord.hh | 290 ++--- game/shared/entity/collision.cc | 350 +++--- game/shared/entity/collision.hh | 42 +- game/shared/entity/factory.cc | 74 +- game/shared/entity/factory.hh | 22 +- game/shared/entity/gravity.cc | 40 +- game/shared/entity/gravity.hh | 28 +- game/shared/entity/grounded.hh | 32 +- game/shared/entity/head.hh | 32 +- game/shared/entity/player.hh | 12 +- game/shared/entity/stasis.cc | 42 +- game/shared/entity/stasis.hh | 32 +- game/shared/entity/transform.cc | 66 +- game/shared/entity/transform.hh | 60 +- game/shared/entity/velocity.cc | 38 +- game/shared/entity/velocity.hh | 38 +- game/shared/game.cc | 246 ++-- game/shared/game.hh | 22 +- game/shared/game_items.cc | 135 +-- game/shared/game_items.hh | 52 +- game/shared/game_voxels.cc | 245 ++-- game/shared/game_voxels.hh | 56 +- game/shared/globals.cc | 24 +- game/shared/globals.hh | 38 +- game/shared/pch.hh | 38 +- game/shared/protocol.cc | 1020 ++++++++-------- game/shared/protocol.hh | 424 +++---- game/shared/splash.cc | 130 +- game/shared/splash.hh | 16 +- game/shared/types.hh | 80 +- game/shared/world/chunk.cc | 140 +-- game/shared/world/chunk.hh | 84 +- game/shared/world/chunk_aabb.cc | 108 +- game/shared/world/chunk_aabb.hh | 66 +- game/shared/world/dimension.cc | 346 +++--- game/shared/world/dimension.hh | 200 +-- game/shared/world/feature.cc | 106 +- game/shared/world/feature.hh | 44 +- game/shared/world/item_registry.cc | 212 ++-- game/shared/world/item_registry.hh | 128 +- game/shared/world/ray_dda.cc | 214 ++-- game/shared/world/ray_dda.hh | 82 +- game/shared/world/voxel_registry.cc | 392 +++--- game/shared/world/voxel_registry.hh | 298 ++--- game/shared/world/voxel_storage.cc | 96 +- game/shared/world/voxel_storage.hh | 40 +- 212 files changed, 17689 insertions(+), 17699 deletions(-) diff --git a/core/config/boolean.cc b/core/config/boolean.cc index 45d5a38..5981b6d 100644 --- a/core/config/boolean.cc +++ b/core/config/boolean.cc @@ -1,43 +1,43 @@ -#include "core/pch.hh" - -#include "core/config/boolean.hh" - -config::Boolean::Boolean(bool default_value) -{ - m_value = default_value; -} - -void config::Boolean::set(std::string_view value) -{ - m_value = from_string(value); -} - -std::string_view config::Boolean::get(void) const -{ - return to_string(m_value); -} - -bool config::Boolean::get_value(void) const -{ - return m_value; -} - -void config::Boolean::set_value(bool value) -{ - m_value = value; -} - -std::string_view config::Boolean::to_string(bool value) -{ - if(value) { - return "true"; - } - else { - return "false"; - } -} - -bool config::Boolean::from_string(std::string_view value) -{ - return value == "true" && value != "false"; -} +#include "core/pch.hh" + +#include "core/config/boolean.hh" + +config::Boolean::Boolean(bool default_value) +{ + m_value = default_value; +} + +void config::Boolean::set(std::string_view value) +{ + m_value = from_string(value); +} + +std::string_view config::Boolean::get(void) const +{ + return to_string(m_value); +} + +bool config::Boolean::get_value(void) const +{ + return m_value; +} + +void config::Boolean::set_value(bool value) +{ + m_value = value; +} + +std::string_view config::Boolean::to_string(bool value) +{ + if(value) { + return "true"; + } + else { + return "false"; + } +} + +bool config::Boolean::from_string(std::string_view value) +{ + return value == "true" && value != "false"; +} diff --git a/core/config/boolean.hh b/core/config/boolean.hh index cfd8b0b..f4d3acd 100644 --- a/core/config/boolean.hh +++ b/core/config/boolean.hh @@ -1,25 +1,25 @@ -#pragma once - -#include "core/config/ivalue.hh" - -namespace config -{ -class Boolean : public IValue { -public: - explicit Boolean(bool default_value = false); - virtual ~Boolean(void) = default; - - virtual void set(std::string_view value) override; - virtual std::string_view get(void) const override; - - bool get_value(void) const; - void set_value(bool value); - -private: - bool m_value; - -public: - static std::string_view to_string(bool value); - static bool from_string(std::string_view value); -}; -} // namespace config +#pragma once + +#include "core/config/ivalue.hh" + +namespace config +{ +class Boolean : public IValue { +public: + explicit Boolean(bool default_value = false); + virtual ~Boolean(void) = default; + + virtual void set(std::string_view value) override; + virtual std::string_view get(void) const override; + + bool get_value(void) const; + void set_value(bool value); + +private: + bool m_value; + +public: + static std::string_view to_string(bool value); + static bool from_string(std::string_view value); +}; +} // namespace config diff --git a/core/config/ivalue.hh b/core/config/ivalue.hh index 13e9a3a..782da76 100644 --- a/core/config/ivalue.hh +++ b/core/config/ivalue.hh @@ -1,11 +1,11 @@ -#pragma once - -namespace config -{ -class IValue { -public: - virtual ~IValue(void) = default; - virtual void set(std::string_view value) = 0; - virtual std::string_view get(void) const = 0; -}; -} // namespace config +#pragma once + +namespace config +{ +class IValue { +public: + virtual ~IValue(void) = default; + virtual void set(std::string_view value) = 0; + virtual std::string_view get(void) const = 0; +}; +} // namespace config diff --git a/core/config/number.hh b/core/config/number.hh index 45d4773..5533459 100644 --- a/core/config/number.hh +++ b/core/config/number.hh @@ -1,130 +1,130 @@ -#pragma once - -#include "core/config/ivalue.hh" - -#include "core/math/concepts.hh" - -namespace config -{ -template -class Number : public IValue { -public: - explicit Number(T default_value = T(0)); - explicit Number(T default_value, T min_value, T max_value); - virtual ~Number(void) = default; - - virtual void set(std::string_view value) override; - virtual std::string_view get(void) const override; - - T get_value(void) const; - void set_value(T value); - - T get_min_value(void) const; - T get_max_value(void) const; - void set_limits(T min_value, T max_value); - -private: - T m_value; - T m_min_value; - T m_max_value; - std::string m_string; -}; -} // namespace config - -namespace config -{ -class Int final : public Number { -public: - using Number::Number; -}; - -class Float final : public Number { -public: - using Number::Number; -}; - -class Unsigned final : public Number { -public: - using Number::Number; -}; - -class Unsigned64 final : public Number { -public: - using Number::Number; -}; - -class SizeType final : public Number { -public: - using Number::Number; -}; -} // namespace config - -template -inline config::Number::Number(T default_value) -{ - m_value = default_value; - m_min_value = std::numeric_limits::lowest(); - m_max_value = std::numeric_limits::max(); - m_string = std::to_string(default_value); -} - -template -inline config::Number::Number(T default_value, T min_value, T max_value) -{ - m_value = default_value; - m_min_value = min_value; - m_max_value = max_value; - m_string = std::to_string(default_value); -} - -template -inline void config::Number::set(std::string_view value) -{ - T parsed_value; - auto result = std::from_chars(value.data(), value.data() + value.size(), parsed_value); - - if(result.ec == std::errc()) { - m_value = std::clamp(parsed_value, m_min_value, m_max_value); - m_string = std::to_string(m_value); - } -} - -template -inline std::string_view config::Number::get(void) const -{ - return m_string; -} - -template -inline T config::Number::get_value(void) const -{ - return m_value; -} - -template -inline void config::Number::set_value(T value) -{ - m_value = std::clamp(value, m_min_value, m_max_value); - m_string = std::to_string(m_value); -} - -template -inline T config::Number::get_min_value(void) const -{ - return m_min_value; -} - -template -inline T config::Number::get_max_value(void) const -{ - return m_max_value; -} - -template -inline void config::Number::set_limits(T min_value, T max_value) -{ - m_min_value = min_value; - m_max_value = max_value; - m_value = std::clamp(m_value, m_min_value, m_max_value); - m_string = std::to_string(m_value); -} +#pragma once + +#include "core/config/ivalue.hh" + +#include "core/math/concepts.hh" + +namespace config +{ +template +class Number : public IValue { +public: + explicit Number(T default_value = T(0)); + explicit Number(T default_value, T min_value, T max_value); + virtual ~Number(void) = default; + + virtual void set(std::string_view value) override; + virtual std::string_view get(void) const override; + + T get_value(void) const; + void set_value(T value); + + T get_min_value(void) const; + T get_max_value(void) const; + void set_limits(T min_value, T max_value); + +private: + T m_value; + T m_min_value; + T m_max_value; + std::string m_string; +}; +} // namespace config + +namespace config +{ +class Int final : public Number { +public: + using Number::Number; +}; + +class Float final : public Number { +public: + using Number::Number; +}; + +class Unsigned final : public Number { +public: + using Number::Number; +}; + +class Unsigned64 final : public Number { +public: + using Number::Number; +}; + +class SizeType final : public Number { +public: + using Number::Number; +}; +} // namespace config + +template +inline config::Number::Number(T default_value) +{ + m_value = default_value; + m_min_value = std::numeric_limits::lowest(); + m_max_value = std::numeric_limits::max(); + m_string = std::to_string(default_value); +} + +template +inline config::Number::Number(T default_value, T min_value, T max_value) +{ + m_value = default_value; + m_min_value = min_value; + m_max_value = max_value; + m_string = std::to_string(default_value); +} + +template +inline void config::Number::set(std::string_view value) +{ + T parsed_value; + auto result = std::from_chars(value.data(), value.data() + value.size(), parsed_value); + + if(result.ec == std::errc()) { + m_value = std::clamp(parsed_value, m_min_value, m_max_value); + m_string = std::to_string(m_value); + } +} + +template +inline std::string_view config::Number::get(void) const +{ + return m_string; +} + +template +inline T config::Number::get_value(void) const +{ + return m_value; +} + +template +inline void config::Number::set_value(T value) +{ + m_value = std::clamp(value, m_min_value, m_max_value); + m_string = std::to_string(m_value); +} + +template +inline T config::Number::get_min_value(void) const +{ + return m_min_value; +} + +template +inline T config::Number::get_max_value(void) const +{ + return m_max_value; +} + +template +inline void config::Number::set_limits(T min_value, T max_value) +{ + m_min_value = min_value; + m_max_value = max_value; + m_value = std::clamp(m_value, m_min_value, m_max_value); + m_string = std::to_string(m_value); +} diff --git a/core/config/string.cc b/core/config/string.cc index 198b448..8fb9d70 100644 --- a/core/config/string.cc +++ b/core/config/string.cc @@ -1,18 +1,18 @@ -#include "core/pch.hh" - -#include "core/config/string.hh" - -config::String::String(std::string_view default_value) -{ - m_value = default_value; -} - -void config::String::set(std::string_view value) -{ - m_value = value; -} - -std::string_view config::String::get(void) const -{ - return m_value; -} +#include "core/pch.hh" + +#include "core/config/string.hh" + +config::String::String(std::string_view default_value) +{ + m_value = default_value; +} + +void config::String::set(std::string_view value) +{ + m_value = value; +} + +std::string_view config::String::get(void) const +{ + return m_value; +} diff --git a/core/config/string.hh b/core/config/string.hh index 8fd3901..d7bbbc1 100644 --- a/core/config/string.hh +++ b/core/config/string.hh @@ -1,31 +1,31 @@ -#pragma once - -#include "core/config/ivalue.hh" - -namespace config -{ -class String : public IValue { -public: - explicit String(std::string_view default_value); - virtual ~String(void) = default; - - virtual void set(std::string_view value) override; - virtual std::string_view get(void) const override; - - constexpr const std::string& get_value(void) const noexcept; - constexpr const char* c_str(void) const noexcept; - -private: - std::string m_value; -}; -} // namespace config - -constexpr const std::string& config::String::get_value(void) const noexcept -{ - return m_value; -} - -constexpr const char* config::String::c_str(void) const noexcept -{ - return m_value.c_str(); -} +#pragma once + +#include "core/config/ivalue.hh" + +namespace config +{ +class String : public IValue { +public: + explicit String(std::string_view default_value); + virtual ~String(void) = default; + + virtual void set(std::string_view value) override; + virtual std::string_view get(void) const override; + + constexpr const std::string& get_value(void) const noexcept; + constexpr const char* c_str(void) const noexcept; + +private: + std::string m_value; +}; +} // namespace config + +constexpr const std::string& config::String::get_value(void) const noexcept +{ + return m_value; +} + +constexpr const char* config::String::c_str(void) const noexcept +{ + return m_value.c_str(); +} diff --git a/core/io/buffer.cc b/core/io/buffer.cc index 02b810e..d3bf7bb 100644 --- a/core/io/buffer.cc +++ b/core/io/buffer.cc @@ -1,345 +1,345 @@ -#include "core/pch.hh" - -#include "core/io/buffer.hh" - -#include "core/math/constexpr.hh" - -io::ReadBuffer::ReadBuffer(const ReadBuffer& other) -{ - reset(other.data(), other.size()); -} - -io::ReadBuffer::ReadBuffer(const void* data, std::size_t size) -{ - assert(data); - - reset(data, size); -} - -io::ReadBuffer::ReadBuffer(const ENetPacket* packet) -{ - assert(packet); - - reset(packet); -} - -io::ReadBuffer::ReadBuffer(PHYSFS_File* file) -{ - assert(file); - - reset(file); -} - -std::size_t io::ReadBuffer::size(void) const -{ - return m_vector.size(); -} - -const std::byte* io::ReadBuffer::data(void) const -{ - return m_vector.data(); -} - -void io::ReadBuffer::reset(const void* data, std::size_t size) -{ - assert(data); - - auto bytes = reinterpret_cast(data); - m_vector.assign(bytes, bytes + size); - m_position = 0U; -} - -void io::ReadBuffer::reset(const ENetPacket* packet) -{ - assert(packet); - - auto bytes_ptr = reinterpret_cast(packet->data); - m_vector.assign(bytes_ptr, bytes_ptr + packet->dataLength); - m_position = 0; -} - -void io::ReadBuffer::reset(PHYSFS_File* file) -{ - assert(file); - - m_vector.resize(PHYSFS_fileLength(file)); - m_position = 0; - - PHYSFS_seek(file, 0); - PHYSFS_readBytes(file, m_vector.data(), m_vector.size()); -} - -template<> -std::byte io::ReadBuffer::read(void) -{ - if(m_position < m_vector.size()) { - auto result = m_vector[m_position]; - m_position += 1U; - return result; - } - - m_position += 1U; - return static_cast(0x00); -} - -template<> -std::uint8_t io::ReadBuffer::read(void) -{ - if((m_position + 1U) <= m_vector.size()) { - auto result = static_cast(m_vector[m_position]); - m_position += 1U; - return result; - } - - m_position += 1U; - return 0; -} - -template<> -std::uint16_t io::ReadBuffer::read(void) -{ - if((m_position + 2U) <= m_vector.size()) { - auto result = UINT16_C(0x0000); - result |= (UINT16_C(0x00FF) & static_cast(m_vector[m_position + 0U])) << 8U; - result |= (UINT16_C(0x00FF) & static_cast(m_vector[m_position + 1U])) << 0U; - m_position += 2U; - return result; - } - - m_position += 2U; - return 0; -} - -template<> -std::uint32_t io::ReadBuffer::read(void) -{ - if((m_position + 4U) <= m_vector.size()) { - auto result = UINT32_C(0x00000000); - result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 0U])) << 24U; - result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 1U])) << 16U; - result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 2U])) << 8U; - result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 3U])) << 0U; - m_position += 4U; - return result; - } - - m_position += 4U; - return 0; -} - -template<> -std::uint64_t io::ReadBuffer::read(void) -{ - if((m_position + 8U) <= m_vector.size()) { - auto result = UINT64_C(0x0000000000000000); - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 0U])) << 56U; - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 1U])) << 48U; - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 2U])) << 40U; - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 3U])) << 32U; - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 4U])) << 24U; - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 5U])) << 16U; - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 6U])) << 8U; - result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 7U])) << 0U; - m_position += 8U; - return result; - } - - m_position += 8U; - return 0; -} - -template<> -float io::ReadBuffer::read(void) -{ - return std::bit_cast(read()); -} - -template<> -std::int8_t io::ReadBuffer::read(void) -{ - return std::bit_cast(read()); -} - -template<> -std::int16_t io::ReadBuffer::read(void) -{ - return std::bit_cast(read()); -} - -template<> -std::int32_t io::ReadBuffer::read(void) -{ - return std::bit_cast(read()); -} - -template<> -std::int64_t io::ReadBuffer::read(void) -{ - return std::bit_cast(read()); -} - -template<> -std::string io::ReadBuffer::read(void) -{ - std::string result; - result.resize(read()); - - for(std::size_t i = 0; i < result.size(); ++i) { - if(m_position < m_vector.size()) { - result[i] = static_cast(m_vector[m_position]); - } - - m_position += 1U; - } - - return result; -} - -void io::ReadBuffer::read(void* buffer, std::size_t size) -{ - auto bytes = reinterpret_cast(buffer); - auto amount_to_read = std::min(size, m_vector.size() - m_position); - - if(amount_to_read > 0) { - std::copy(m_vector.cbegin() + m_position, m_vector.cbegin() + m_position + amount_to_read, bytes); - } - - m_position += size; -} - -io::WriteBuffer::WriteBuffer(const WriteBuffer& other) -{ - m_vector = other.m_vector; -} - -std::size_t io::WriteBuffer::size(void) const -{ - return m_vector.size(); -} - -const std::byte* io::WriteBuffer::data(void) const -{ - return m_vector.data(); -} - -void io::WriteBuffer::reset(void) -{ - m_vector.clear(); -} - -void io::WriteBuffer::write(const WriteBuffer& other) -{ - m_vector.insert(m_vector.end(), other.m_vector.begin(), other.m_vector.end()); -} - -void io::WriteBuffer::write(const void* data, std::size_t size) -{ - assert(data); - - auto bytes = reinterpret_cast(data); - m_vector.insert(m_vector.end(), bytes, bytes + size); -} - -template<> -void io::WriteBuffer::write(const std::byte value) -{ - m_vector.push_back(value); -} - -template<> -void io::WriteBuffer::write(const std::uint8_t value) -{ - m_vector.push_back(static_cast(value)); -} - -template<> -void io::WriteBuffer::write(const std::uint16_t value) -{ - m_vector.push_back(static_cast(UINT16_C(0xFF) & ((value & UINT16_C(0xFF00)) >> 8U))); - m_vector.push_back(static_cast(UINT16_C(0xFF) & ((value & UINT16_C(0x00FF)) >> 0U))); -} - -template<> -void io::WriteBuffer::write(const std::uint32_t value) -{ - m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0xFF000000)) >> 24U))); - m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0x00FF0000)) >> 16U))); - m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0x0000FF00)) >> 8U))); - m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0x000000FF)) >> 0U))); -} - -template<> -void io::WriteBuffer::write(const std::uint64_t value) -{ - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0xFF00000000000000)) >> 56U))); - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x00FF000000000000)) >> 48U))); - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x0000FF0000000000)) >> 40U))); - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x000000FF00000000)) >> 32U))); - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x00000000FF000000)) >> 24U))); - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x0000000000FF0000)) >> 16U))); - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x000000000000FF00)) >> 8U))); - m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x00000000000000FF)) >> 0U))); -} - -template<> -void io::WriteBuffer::write(const float value) -{ - write(std::bit_cast(value)); -} - -template<> -void io::WriteBuffer::write(const std::int8_t value) -{ - write(std::bit_cast(value)); -} - -template<> -void io::WriteBuffer::write(const std::int16_t value) -{ - write(std::bit_cast(value)); -} - -template<> -void io::WriteBuffer::write(const std::int32_t value) -{ - write(std::bit_cast(value)); -} - -template<> -void io::WriteBuffer::write(const std::int64_t value) -{ - write(std::bit_cast(value)); -} - -template<> -void io::WriteBuffer::write(const std::string_view value) -{ - write(value.size()); - - for(const auto& character : value) { - m_vector.push_back(static_cast(character)); - } -} - -PHYSFS_File* io::WriteBuffer::to_file(const std::string& path, bool append) const -{ - PHYSFS_File* file = nullptr; - - if(append) { - file = PHYSFS_openAppend(path.c_str()); - } - else { - file = PHYSFS_openWrite(path.c_str()); - } - - if(file) { - PHYSFS_writeBytes(file, m_vector.data(), m_vector.size()); - } - - return file; -} - -ENetPacket* io::WriteBuffer::to_packet(enet_uint32 flags) const -{ - return enet_packet_create(m_vector.data(), m_vector.size(), flags); -} +#include "core/pch.hh" + +#include "core/io/buffer.hh" + +#include "core/math/constexpr.hh" + +io::ReadBuffer::ReadBuffer(const ReadBuffer& other) +{ + reset(other.data(), other.size()); +} + +io::ReadBuffer::ReadBuffer(const void* data, std::size_t size) +{ + assert(data); + + reset(data, size); +} + +io::ReadBuffer::ReadBuffer(const ENetPacket* packet) +{ + assert(packet); + + reset(packet); +} + +io::ReadBuffer::ReadBuffer(PHYSFS_File* file) +{ + assert(file); + + reset(file); +} + +std::size_t io::ReadBuffer::size(void) const +{ + return m_vector.size(); +} + +const std::byte* io::ReadBuffer::data(void) const +{ + return m_vector.data(); +} + +void io::ReadBuffer::reset(const void* data, std::size_t size) +{ + assert(data); + + auto bytes = reinterpret_cast(data); + m_vector.assign(bytes, bytes + size); + m_position = 0U; +} + +void io::ReadBuffer::reset(const ENetPacket* packet) +{ + assert(packet); + + auto bytes_ptr = reinterpret_cast(packet->data); + m_vector.assign(bytes_ptr, bytes_ptr + packet->dataLength); + m_position = 0; +} + +void io::ReadBuffer::reset(PHYSFS_File* file) +{ + assert(file); + + m_vector.resize(PHYSFS_fileLength(file)); + m_position = 0; + + PHYSFS_seek(file, 0); + PHYSFS_readBytes(file, m_vector.data(), m_vector.size()); +} + +template<> +std::byte io::ReadBuffer::read(void) +{ + if(m_position < m_vector.size()) { + auto result = m_vector[m_position]; + m_position += 1U; + return result; + } + + m_position += 1U; + return static_cast(0x00); +} + +template<> +std::uint8_t io::ReadBuffer::read(void) +{ + if((m_position + 1U) <= m_vector.size()) { + auto result = static_cast(m_vector[m_position]); + m_position += 1U; + return result; + } + + m_position += 1U; + return 0; +} + +template<> +std::uint16_t io::ReadBuffer::read(void) +{ + if((m_position + 2U) <= m_vector.size()) { + auto result = UINT16_C(0x0000); + result |= (UINT16_C(0x00FF) & static_cast(m_vector[m_position + 0U])) << 8U; + result |= (UINT16_C(0x00FF) & static_cast(m_vector[m_position + 1U])) << 0U; + m_position += 2U; + return result; + } + + m_position += 2U; + return 0; +} + +template<> +std::uint32_t io::ReadBuffer::read(void) +{ + if((m_position + 4U) <= m_vector.size()) { + auto result = UINT32_C(0x00000000); + result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 0U])) << 24U; + result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 1U])) << 16U; + result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 2U])) << 8U; + result |= (UINT32_C(0x000000FF) & static_cast(m_vector[m_position + 3U])) << 0U; + m_position += 4U; + return result; + } + + m_position += 4U; + return 0; +} + +template<> +std::uint64_t io::ReadBuffer::read(void) +{ + if((m_position + 8U) <= m_vector.size()) { + auto result = UINT64_C(0x0000000000000000); + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 0U])) << 56U; + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 1U])) << 48U; + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 2U])) << 40U; + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 3U])) << 32U; + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 4U])) << 24U; + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 5U])) << 16U; + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 6U])) << 8U; + result |= (UINT64_C(0x00000000000000FF) & static_cast(m_vector[m_position + 7U])) << 0U; + m_position += 8U; + return result; + } + + m_position += 8U; + return 0; +} + +template<> +float io::ReadBuffer::read(void) +{ + return std::bit_cast(read()); +} + +template<> +std::int8_t io::ReadBuffer::read(void) +{ + return std::bit_cast(read()); +} + +template<> +std::int16_t io::ReadBuffer::read(void) +{ + return std::bit_cast(read()); +} + +template<> +std::int32_t io::ReadBuffer::read(void) +{ + return std::bit_cast(read()); +} + +template<> +std::int64_t io::ReadBuffer::read(void) +{ + return std::bit_cast(read()); +} + +template<> +std::string io::ReadBuffer::read(void) +{ + std::string result; + result.resize(read()); + + for(std::size_t i = 0; i < result.size(); ++i) { + if(m_position < m_vector.size()) { + result[i] = static_cast(m_vector[m_position]); + } + + m_position += 1U; + } + + return result; +} + +void io::ReadBuffer::read(void* buffer, std::size_t size) +{ + auto bytes = reinterpret_cast(buffer); + auto amount_to_read = std::min(size, m_vector.size() - m_position); + + if(amount_to_read > 0) { + std::copy(m_vector.cbegin() + m_position, m_vector.cbegin() + m_position + amount_to_read, bytes); + } + + m_position += size; +} + +io::WriteBuffer::WriteBuffer(const WriteBuffer& other) +{ + m_vector = other.m_vector; +} + +std::size_t io::WriteBuffer::size(void) const +{ + return m_vector.size(); +} + +const std::byte* io::WriteBuffer::data(void) const +{ + return m_vector.data(); +} + +void io::WriteBuffer::reset(void) +{ + m_vector.clear(); +} + +void io::WriteBuffer::write(const WriteBuffer& other) +{ + m_vector.insert(m_vector.end(), other.m_vector.begin(), other.m_vector.end()); +} + +void io::WriteBuffer::write(const void* data, std::size_t size) +{ + assert(data); + + auto bytes = reinterpret_cast(data); + m_vector.insert(m_vector.end(), bytes, bytes + size); +} + +template<> +void io::WriteBuffer::write(const std::byte value) +{ + m_vector.push_back(value); +} + +template<> +void io::WriteBuffer::write(const std::uint8_t value) +{ + m_vector.push_back(static_cast(value)); +} + +template<> +void io::WriteBuffer::write(const std::uint16_t value) +{ + m_vector.push_back(static_cast(UINT16_C(0xFF) & ((value & UINT16_C(0xFF00)) >> 8U))); + m_vector.push_back(static_cast(UINT16_C(0xFF) & ((value & UINT16_C(0x00FF)) >> 0U))); +} + +template<> +void io::WriteBuffer::write(const std::uint32_t value) +{ + m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0xFF000000)) >> 24U))); + m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0x00FF0000)) >> 16U))); + m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0x0000FF00)) >> 8U))); + m_vector.push_back(static_cast(UINT32_C(0xFF) & ((value & UINT32_C(0x000000FF)) >> 0U))); +} + +template<> +void io::WriteBuffer::write(const std::uint64_t value) +{ + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0xFF00000000000000)) >> 56U))); + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x00FF000000000000)) >> 48U))); + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x0000FF0000000000)) >> 40U))); + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x000000FF00000000)) >> 32U))); + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x00000000FF000000)) >> 24U))); + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x0000000000FF0000)) >> 16U))); + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x000000000000FF00)) >> 8U))); + m_vector.push_back(static_cast(UINT64_C(0xFF) & ((value & UINT64_C(0x00000000000000FF)) >> 0U))); +} + +template<> +void io::WriteBuffer::write(const float value) +{ + write(std::bit_cast(value)); +} + +template<> +void io::WriteBuffer::write(const std::int8_t value) +{ + write(std::bit_cast(value)); +} + +template<> +void io::WriteBuffer::write(const std::int16_t value) +{ + write(std::bit_cast(value)); +} + +template<> +void io::WriteBuffer::write(const std::int32_t value) +{ + write(std::bit_cast(value)); +} + +template<> +void io::WriteBuffer::write(const std::int64_t value) +{ + write(std::bit_cast(value)); +} + +template<> +void io::WriteBuffer::write(const std::string_view value) +{ + write(value.size()); + + for(const auto& character : value) { + m_vector.push_back(static_cast(character)); + } +} + +PHYSFS_File* io::WriteBuffer::to_file(const std::string& path, bool append) const +{ + PHYSFS_File* file = nullptr; + + if(append) { + file = PHYSFS_openAppend(path.c_str()); + } + else { + file = PHYSFS_openWrite(path.c_str()); + } + + if(file) { + PHYSFS_writeBytes(file, m_vector.data(), m_vector.size()); + } + + return file; +} + +ENetPacket* io::WriteBuffer::to_packet(enet_uint32 flags) const +{ + return enet_packet_create(m_vector.data(), m_vector.size(), flags); +} diff --git a/core/io/buffer.hh b/core/io/buffer.hh index 96a37b1..5f1ab66 100644 --- a/core/io/buffer.hh +++ b/core/io/buffer.hh @@ -1,88 +1,88 @@ -namespace io -{ -class ReadBuffer final { -public: - ReadBuffer(void) = default; - explicit ReadBuffer(const ReadBuffer& other); - explicit ReadBuffer(const void* data, std::size_t size); - explicit ReadBuffer(const ENetPacket* packet); - explicit ReadBuffer(PHYSFS_File* file); - virtual ~ReadBuffer(void) = default; - - std::size_t size(void) const; - const std::byte* data(void) const; - - void reset(const void* data, std::size_t size); - void reset(const ENetPacket* packet); - void reset(PHYSFS_File* file); - - constexpr void rewind(void); - constexpr bool is_ended(void) const; - - void read(void* buffer, std::size_t size); - - template - T read(void); - - template - ReadBuffer& operator>>(T& value); - -private: - std::vector m_vector; - std::size_t m_position; -}; -} // namespace io - -namespace io -{ -class WriteBuffer final { -public: - WriteBuffer(void) = default; - explicit WriteBuffer(const WriteBuffer& other); - virtual ~WriteBuffer(void) = default; - - std::size_t size(void) const; - const std::byte* data(void) const; - - void reset(void); - - void write(const WriteBuffer& other); - void write(const void* data, std::size_t size); - - template - void write(const T value); - - template - WriteBuffer& operator<<(const T value); - - PHYSFS_File* to_file(const std::string& path, bool append = false) const; - ENetPacket* to_packet(enet_uint32 flags = ENET_PACKET_FLAG_RELIABLE) const; - -private: - std::vector m_vector; -}; -} // namespace io - -constexpr void io::ReadBuffer::rewind(void) -{ - m_position = 0; -} - -constexpr bool io::ReadBuffer::is_ended(void) const -{ - return m_position >= m_vector.size(); -} - -template -io::ReadBuffer& io::ReadBuffer::operator>>(T& value) -{ - value = read(); - return *this; -} - -template -io::WriteBuffer& io::WriteBuffer::operator<<(const T value) -{ - write(value); - return *this; -} +namespace io +{ +class ReadBuffer final { +public: + ReadBuffer(void) = default; + explicit ReadBuffer(const ReadBuffer& other); + explicit ReadBuffer(const void* data, std::size_t size); + explicit ReadBuffer(const ENetPacket* packet); + explicit ReadBuffer(PHYSFS_File* file); + virtual ~ReadBuffer(void) = default; + + std::size_t size(void) const; + const std::byte* data(void) const; + + void reset(const void* data, std::size_t size); + void reset(const ENetPacket* packet); + void reset(PHYSFS_File* file); + + constexpr void rewind(void); + constexpr bool is_ended(void) const; + + void read(void* buffer, std::size_t size); + + template + T read(void); + + template + ReadBuffer& operator>>(T& value); + +private: + std::vector m_vector; + std::size_t m_position; +}; +} // namespace io + +namespace io +{ +class WriteBuffer final { +public: + WriteBuffer(void) = default; + explicit WriteBuffer(const WriteBuffer& other); + virtual ~WriteBuffer(void) = default; + + std::size_t size(void) const; + const std::byte* data(void) const; + + void reset(void); + + void write(const WriteBuffer& other); + void write(const void* data, std::size_t size); + + template + void write(const T value); + + template + WriteBuffer& operator<<(const T value); + + PHYSFS_File* to_file(const std::string& path, bool append = false) const; + ENetPacket* to_packet(enet_uint32 flags = ENET_PACKET_FLAG_RELIABLE) const; + +private: + std::vector m_vector; +}; +} // namespace io + +constexpr void io::ReadBuffer::rewind(void) +{ + m_position = 0; +} + +constexpr bool io::ReadBuffer::is_ended(void) const +{ + return m_position >= m_vector.size(); +} + +template +io::ReadBuffer& io::ReadBuffer::operator>>(T& value) +{ + value = read(); + return *this; +} + +template +io::WriteBuffer& io::WriteBuffer::operator<<(const T value) +{ + write(value); + return *this; +} diff --git a/core/io/cmdline.cc b/core/io/cmdline.cc index 7a00f37..a876ace 100644 --- a/core/io/cmdline.cc +++ b/core/io/cmdline.cc @@ -1,95 +1,95 @@ -#include "core/pch.hh" - -#include "core/io/cmdline.hh" - -// Valid options always start with OPTION_PREFIX, can contain -// a bunch of OPTION_PREFIX'es inside and never end with one -constexpr static char OPTION_PREFIX = '-'; - -static std::unordered_map options; - -static inline bool is_option_string(const std::string& string) -{ - if(string.find_last_of(OPTION_PREFIX) >= (string.size() - 1)) { - return false; - } - - return string[0] == OPTION_PREFIX; -} - -static inline std::string get_option(const std::string& string) -{ - std::size_t i; - for(i = 0; string[i] == OPTION_PREFIX; ++i) { - // empty - } - - return std::string(string.cbegin() + i, string.cend()); -} - -void io::cmdline::create(int argc, char** argv) -{ - for(int idx = 1; idx < argc; ++idx) { - std::string string = argv[idx]; - - if(!is_option_string(string)) { - spdlog::warn("cmdline: non-argument at {}: {}", idx, string); - continue; - } - - auto option_string = get_option(string); - auto next_idx = idx + 1; - - if(next_idx < argc) { - std::string argument = argv[next_idx]; - - if(!is_option_string(argument)) { - options.insert_or_assign(option_string, argument); - idx = next_idx; - continue; - } - } - - // The option is either last or has no - // argument (happens when there is a valid - // option right next to the one we're parsing) - options.insert_or_assign(option_string, std::string()); - } -} - -void io::cmdline::insert(std::string_view option) -{ - options.insert_or_assign(std::string(option), std::string()); -} - -void io::cmdline::insert(std::string_view option, std::string_view argument) -{ - options.insert_or_assign(std::string(option), std::string(argument)); -} - -std::string_view io::cmdline::get(std::string_view option, std::string_view fallback) -{ - auto it = options.find(std::string(option)); - - if(it == options.cend()) { - return fallback; - } - - return it->second; -} - -const char* io::cmdline::get_cstr(std::string_view option, const char* fallback) -{ - auto it = options.find(std::string(option)); - - if(it == options.cend()) { - return fallback; - } - - return it->second.c_str(); -} - -bool io::cmdline::contains(std::string_view option) -{ - return options.count(std::string(option)); -} +#include "core/pch.hh" + +#include "core/io/cmdline.hh" + +// Valid options always start with OPTION_PREFIX, can contain +// a bunch of OPTION_PREFIX'es inside and never end with one +constexpr static char OPTION_PREFIX = '-'; + +static std::unordered_map options; + +static inline bool is_option_string(const std::string& string) +{ + if(string.find_last_of(OPTION_PREFIX) >= (string.size() - 1)) { + return false; + } + + return string[0] == OPTION_PREFIX; +} + +static inline std::string get_option(const std::string& string) +{ + std::size_t i; + for(i = 0; string[i] == OPTION_PREFIX; ++i) { + // empty + } + + return std::string(string.cbegin() + i, string.cend()); +} + +void io::cmdline::create(int argc, char** argv) +{ + for(int idx = 1; idx < argc; ++idx) { + std::string string = argv[idx]; + + if(!is_option_string(string)) { + spdlog::warn("cmdline: non-argument at {}: {}", idx, string); + continue; + } + + auto option_string = get_option(string); + auto next_idx = idx + 1; + + if(next_idx < argc) { + std::string argument = argv[next_idx]; + + if(!is_option_string(argument)) { + options.insert_or_assign(option_string, argument); + idx = next_idx; + continue; + } + } + + // The option is either last or has no + // argument (happens when there is a valid + // option right next to the one we're parsing) + options.insert_or_assign(option_string, std::string()); + } +} + +void io::cmdline::insert(std::string_view option) +{ + options.insert_or_assign(std::string(option), std::string()); +} + +void io::cmdline::insert(std::string_view option, std::string_view argument) +{ + options.insert_or_assign(std::string(option), std::string(argument)); +} + +std::string_view io::cmdline::get(std::string_view option, std::string_view fallback) +{ + auto it = options.find(std::string(option)); + + if(it == options.cend()) { + return fallback; + } + + return it->second; +} + +const char* io::cmdline::get_cstr(std::string_view option, const char* fallback) +{ + auto it = options.find(std::string(option)); + + if(it == options.cend()) { + return fallback; + } + + return it->second.c_str(); +} + +bool io::cmdline::contains(std::string_view option) +{ + return options.count(std::string(option)); +} diff --git a/core/io/cmdline.hh b/core/io/cmdline.hh index e90433c..6e2ab9a 100644 --- a/core/io/cmdline.hh +++ b/core/io/cmdline.hh @@ -1,11 +1,11 @@ -#pragma once - -namespace io::cmdline -{ -void create(int argc, char** argv); -void insert(std::string_view option); -void insert(std::string_view option, std::string_view argument); -std::string_view get(std::string_view option, std::string_view fallback = ""); -const char* get_cstr(std::string_view option, const char* fallback = nullptr); -bool contains(std::string_view option); -} // namespace io::cmdline +#pragma once + +namespace io::cmdline +{ +void create(int argc, char** argv); +void insert(std::string_view option); +void insert(std::string_view option, std::string_view argument); +std::string_view get(std::string_view option, std::string_view fallback = ""); +const char* get_cstr(std::string_view option, const char* fallback = nullptr); +bool contains(std::string_view option); +} // namespace io::cmdline diff --git a/core/io/config_map.cc b/core/io/config_map.cc index d22913e..24206f2 100644 --- a/core/io/config_map.cc +++ b/core/io/config_map.cc @@ -1,136 +1,136 @@ -#include "core/pch.hh" - -#include "core/io/config_map.hh" - -#include "core/config/ivalue.hh" - -#include "core/io/cmdline.hh" - -#include "core/utils/string.hh" - -#include "core/version.hh" - -void io::ConfigMap::load_cmdline(void) -{ - for(auto it : m_values) { - if(auto value = io::cmdline::get_cstr(it.first.c_str())) { - it.second->set(value); - } - } -} - -bool io::ConfigMap::load_file(std::string_view path) -{ - if(auto file = PHYSFS_openRead(std::string(path).c_str())) { - auto source = std::string(PHYSFS_fileLength(file), char(0x00)); - PHYSFS_readBytes(file, source.data(), source.size()); - PHYSFS_close(file); - - std::string line; - std::string kv_string; - std::istringstream stream(source); - - while(std::getline(stream, line)) { - auto comment = line.find_first_of('#'); - - if(comment == std::string::npos) { - kv_string = utils::trim_whitespace(line); - } - else { - kv_string = utils::trim_whitespace(line.substr(0, comment)); - } - - if(utils::is_whitespace(kv_string)) { - // Ignore empty or commented out lines - continue; - } - - auto separator = kv_string.find('='); - - if(separator == std::string::npos) { - spdlog::warn("config: {}: invalid line: {}", path, line); - continue; - } - - auto kv_name = utils::trim_whitespace(kv_string.substr(0, separator)); - auto kv_value = utils::trim_whitespace(kv_string.substr(separator + 1)); - - auto kv_pair = m_values.find(kv_name); - - if(kv_pair == m_values.cend()) { - spdlog::warn("config: {}: unknown key: {}", path, kv_name); - continue; - } - - kv_pair->second->set(kv_value.c_str()); - } - - return true; - } - - return false; -} - -bool io::ConfigMap::save_file(std::string_view path) const -{ - std::ostringstream stream; - - auto curtime = std::time(nullptr); - - stream << "# Voxelius " << version::semver << " configuration file" << std::endl; - stream << "# Generated at: " << std::put_time(std::gmtime(&curtime), "%Y-%m-%d %H:%M:%S %z") << std::endl << std::endl; - - for(const auto& it : m_values) { - stream << it.first << "="; - stream << it.second->get(); - stream << std::endl; - } - - if(auto file = PHYSFS_openWrite(std::string(path).c_str())) { - auto source = stream.str(); - PHYSFS_writeBytes(file, source.data(), source.size()); - PHYSFS_close(file); - return true; - } - - return false; -} - -bool io::ConfigMap::set_value(std::string_view name, std::string_view value) -{ - auto kv_pair = m_values.find(std::string(name)); - - if(kv_pair != m_values.cend()) { - kv_pair->second->set(value); - return true; - } - - return false; -} - -std::string_view io::ConfigMap::get_value(std::string_view name) const -{ - auto kv_pair = m_values.find(std::string(name)); - if(kv_pair != m_values.cend()) { - return kv_pair->second->get(); - } - - return std::string_view(); -} - -void io::ConfigMap::add_value(std::string_view name, config::IValue& vref) -{ - m_values.insert_or_assign(std::string(name), &vref); -} - -const config::IValue* io::ConfigMap::find(std::string_view name) const -{ - auto kv_pair = m_values.find(std::string(name)); - - if(kv_pair != m_values.cend()) { - return kv_pair->second; - } - else { - return nullptr; - } -} +#include "core/pch.hh" + +#include "core/io/config_map.hh" + +#include "core/config/ivalue.hh" + +#include "core/io/cmdline.hh" + +#include "core/utils/string.hh" + +#include "core/version.hh" + +void io::ConfigMap::load_cmdline(void) +{ + for(auto it : m_values) { + if(auto value = io::cmdline::get_cstr(it.first.c_str())) { + it.second->set(value); + } + } +} + +bool io::ConfigMap::load_file(std::string_view path) +{ + if(auto file = PHYSFS_openRead(std::string(path).c_str())) { + auto source = std::string(PHYSFS_fileLength(file), char(0x00)); + PHYSFS_readBytes(file, source.data(), source.size()); + PHYSFS_close(file); + + std::string line; + std::string kv_string; + std::istringstream stream(source); + + while(std::getline(stream, line)) { + auto comment = line.find_first_of('#'); + + if(comment == std::string::npos) { + kv_string = utils::trim_whitespace(line); + } + else { + kv_string = utils::trim_whitespace(line.substr(0, comment)); + } + + if(utils::is_whitespace(kv_string)) { + // Ignore empty or commented out lines + continue; + } + + auto separator = kv_string.find('='); + + if(separator == std::string::npos) { + spdlog::warn("config: {}: invalid line: {}", path, line); + continue; + } + + auto kv_name = utils::trim_whitespace(kv_string.substr(0, separator)); + auto kv_value = utils::trim_whitespace(kv_string.substr(separator + 1)); + + auto kv_pair = m_values.find(kv_name); + + if(kv_pair == m_values.cend()) { + spdlog::warn("config: {}: unknown key: {}", path, kv_name); + continue; + } + + kv_pair->second->set(kv_value.c_str()); + } + + return true; + } + + return false; +} + +bool io::ConfigMap::save_file(std::string_view path) const +{ + std::ostringstream stream; + + auto curtime = std::time(nullptr); + + stream << "# Voxelius " << version::semver << " configuration file" << std::endl; + stream << "# Generated at: " << std::put_time(std::gmtime(&curtime), "%Y-%m-%d %H:%M:%S %z") << std::endl << std::endl; + + for(const auto& it : m_values) { + stream << it.first << "="; + stream << it.second->get(); + stream << std::endl; + } + + if(auto file = PHYSFS_openWrite(std::string(path).c_str())) { + auto source = stream.str(); + PHYSFS_writeBytes(file, source.data(), source.size()); + PHYSFS_close(file); + return true; + } + + return false; +} + +bool io::ConfigMap::set_value(std::string_view name, std::string_view value) +{ + auto kv_pair = m_values.find(std::string(name)); + + if(kv_pair != m_values.cend()) { + kv_pair->second->set(value); + return true; + } + + return false; +} + +std::string_view io::ConfigMap::get_value(std::string_view name) const +{ + auto kv_pair = m_values.find(std::string(name)); + if(kv_pair != m_values.cend()) { + return kv_pair->second->get(); + } + + return std::string_view(); +} + +void io::ConfigMap::add_value(std::string_view name, config::IValue& vref) +{ + m_values.insert_or_assign(std::string(name), &vref); +} + +const config::IValue* io::ConfigMap::find(std::string_view name) const +{ + auto kv_pair = m_values.find(std::string(name)); + + if(kv_pair != m_values.cend()) { + return kv_pair->second; + } + else { + return nullptr; + } +} diff --git a/core/io/config_map.hh b/core/io/config_map.hh index b0cd579..6b99564 100644 --- a/core/io/config_map.hh +++ b/core/io/config_map.hh @@ -1,29 +1,29 @@ -#pragma once - -namespace config -{ -class IValue; -} // namespace config - -namespace io -{ -class ConfigMap final { -public: - ConfigMap(void) = default; - virtual ~ConfigMap(void) = default; - - void load_cmdline(void); - bool load_file(std::string_view path); - bool save_file(std::string_view path) const; - - bool set_value(std::string_view name, std::string_view value); - std::string_view get_value(std::string_view name) const; - - void add_value(std::string_view name, config::IValue& vref); - - const config::IValue* find(std::string_view name) const; - -private: - std::unordered_map m_values; -}; -} // namespace io +#pragma once + +namespace config +{ +class IValue; +} // namespace config + +namespace io +{ +class ConfigMap final { +public: + ConfigMap(void) = default; + virtual ~ConfigMap(void) = default; + + void load_cmdline(void); + bool load_file(std::string_view path); + bool save_file(std::string_view path) const; + + bool set_value(std::string_view name, std::string_view value); + std::string_view get_value(std::string_view name) const; + + void add_value(std::string_view name, config::IValue& vref); + + const config::IValue* find(std::string_view name) const; + +private: + std::unordered_map m_values; +}; +} // namespace io diff --git a/core/math/aabb.cc b/core/math/aabb.cc index f5c7e14..1111149 100644 --- a/core/math/aabb.cc +++ b/core/math/aabb.cc @@ -1,59 +1,59 @@ -#include "core/pch.hh" - -#include "core/math/aabb.hh" - -math::AABB::AABB(const glm::fvec3& min, const glm::fvec3& max) -{ - set_bounds(min, max); -} - -void math::AABB::set_bounds(const glm::fvec3& min, const glm::fvec3& max) -{ - this->min = min; - this->max = max; -} - -void math::AABB::set_offset(const glm::fvec3& base, const glm::fvec3& size) -{ - this->min = base; - this->max = base + size; -} - -bool math::AABB::contains(const glm::fvec3& point) const -{ - auto result = true; - result = result && (point.x >= min.x) && (point.x <= max.x); - result = result && (point.y >= min.y) && (point.y <= max.y); - result = result && (point.z >= min.z) && (point.z <= max.z); - return result; -} - -bool math::AABB::intersect(const AABB& other_box) const -{ - auto result = true; - result = result && (min.x < other_box.max.x) && (max.x > other_box.min.x); - result = result && (min.y < other_box.max.y) && (max.y > other_box.min.y); - result = result && (min.z < other_box.max.z) && (max.z > other_box.min.z); - return result; -} - -math::AABB math::AABB::combine_with(const math::AABB& other_box) const -{ - AABB result; - result.set_bounds(min, other_box.max); - return result; -} - -math::AABB math::AABB::multiply_with(const math::AABB& other_box) const -{ - AABB result; - result.set_bounds(other_box.min, max); - return result; -} - -math::AABB math::AABB::push(const glm::fvec3& vector) const -{ - AABB result; - result.set_bounds(min + vector, max + vector); - return result; -} +#include "core/pch.hh" + +#include "core/math/aabb.hh" + +math::AABB::AABB(const glm::fvec3& min, const glm::fvec3& max) +{ + set_bounds(min, max); +} + +void math::AABB::set_bounds(const glm::fvec3& min, const glm::fvec3& max) +{ + this->min = min; + this->max = max; +} + +void math::AABB::set_offset(const glm::fvec3& base, const glm::fvec3& size) +{ + this->min = base; + this->max = base + size; +} + +bool math::AABB::contains(const glm::fvec3& point) const +{ + auto result = true; + result = result && (point.x >= min.x) && (point.x <= max.x); + result = result && (point.y >= min.y) && (point.y <= max.y); + result = result && (point.z >= min.z) && (point.z <= max.z); + return result; +} + +bool math::AABB::intersect(const AABB& other_box) const +{ + auto result = true; + result = result && (min.x < other_box.max.x) && (max.x > other_box.min.x); + result = result && (min.y < other_box.max.y) && (max.y > other_box.min.y); + result = result && (min.z < other_box.max.z) && (max.z > other_box.min.z); + return result; +} + +math::AABB math::AABB::combine_with(const math::AABB& other_box) const +{ + AABB result; + result.set_bounds(min, other_box.max); + return result; +} + +math::AABB math::AABB::multiply_with(const math::AABB& other_box) const +{ + AABB result; + result.set_bounds(other_box.min, max); + return result; +} + +math::AABB math::AABB::push(const glm::fvec3& vector) const +{ + AABB result; + result.set_bounds(min + vector, max + vector); + return result; +} diff --git a/core/math/aabb.hh b/core/math/aabb.hh index b843cd9..bff8e04 100644 --- a/core/math/aabb.hh +++ b/core/math/aabb.hh @@ -1,28 +1,28 @@ -#pragma once - -namespace math -{ -class AABB final { -public: - AABB(void) = default; - explicit AABB(const glm::fvec3& min, const glm::fvec3& max); - virtual ~AABB(void) = default; - - void set_bounds(const glm::fvec3& min, const glm::fvec3& max); - void set_offset(const glm::fvec3& base, const glm::fvec3& size); - - const glm::fvec3& get_min(void) const; - const glm::fvec3& get_max(void) const; - - bool contains(const glm::fvec3& point) const; - bool intersect(const AABB& other_box) const; - - AABB combine_with(const AABB& other_box) const; - AABB multiply_with(const AABB& other_box) const; - AABB push(const glm::fvec3& vector) const; - -public: - glm::fvec3 min; - glm::fvec3 max; -}; -} // namespace math +#pragma once + +namespace math +{ +class AABB final { +public: + AABB(void) = default; + explicit AABB(const glm::fvec3& min, const glm::fvec3& max); + virtual ~AABB(void) = default; + + void set_bounds(const glm::fvec3& min, const glm::fvec3& max); + void set_offset(const glm::fvec3& base, const glm::fvec3& size); + + const glm::fvec3& get_min(void) const; + const glm::fvec3& get_max(void) const; + + bool contains(const glm::fvec3& point) const; + bool intersect(const AABB& other_box) const; + + AABB combine_with(const AABB& other_box) const; + AABB multiply_with(const AABB& other_box) const; + AABB push(const glm::fvec3& vector) const; + +public: + glm::fvec3 min; + glm::fvec3 max; +}; +} // namespace math diff --git a/core/math/angles.hh b/core/math/angles.hh index 174f320..edc2f65 100644 --- a/core/math/angles.hh +++ b/core/math/angles.hh @@ -1,103 +1,103 @@ -#pragma once - -#include "core/math/constexpr.hh" - -constexpr float A180 = math::radians(180.0f); -constexpr float A360 = math::radians(360.0f); - -namespace math -{ -float wrap_180(float angle); -float wrap_360(float angle); -} // namespace math - -namespace math -{ -glm::fvec3 wrap_180(const glm::fvec3& angles); -glm::fvec3 wrap_360(const glm::fvec3& angles); -} // namespace math - -namespace math -{ -void vectors(const glm::fvec3& angles, glm::fvec3& forward); -void vectors(const glm::fvec3& angles, glm::fvec3* forward, glm::fvec3* right, glm::fvec3* up); -} // namespace math - -inline float math::wrap_180(float angle) -{ - const auto result = std::fmod(angle + A180, A360); - - if(result < 0.0f) { - return result + A180; - } - - return result - A180; -} - -inline float math::wrap_360(float angle) -{ - return std::fmod(std::fmod(angle, A360) + A360, A360); -} - -inline glm::fvec3 math::wrap_180(const glm::fvec3& angles) -{ - return glm::fvec3 { - math::wrap_180(angles.x), - math::wrap_180(angles.y), - math::wrap_180(angles.z), - }; -} - -inline glm::fvec3 math::wrap_360(const glm::fvec3& angles) -{ - return glm::fvec3 { - math::wrap_360(angles.x), - math::wrap_360(angles.y), - math::wrap_360(angles.z), - }; -} - -inline void math::vectors(const glm::fvec3& angles, glm::fvec3& forward) -{ - const float cosp = std::cos(angles.x); - const float cosy = std::cos(angles.y); - const float sinp = std::sin(angles.x); - const float siny = std::sin(angles.y); - - forward.x = cosp * siny * (-1.0f); - forward.y = sinp; - forward.z = cosp * cosy * (-1.0f); -} - -inline void math::vectors(const glm::fvec3& angles, glm::fvec3* forward, glm::fvec3* right, glm::fvec3* up) -{ - if(!forward && !right && !up) { - // There's no point in figuring out - // direction vectors if nothing is passed - // in the function to store that stuff in - return; - } - - const auto pcv = glm::cos(angles); - const auto psv = glm::sin(angles); - const auto ncv = pcv * (-1.0f); - const auto nsv = psv * (-1.0f); - - if(forward) { - forward->x = pcv.x * nsv.y; - forward->y = psv.x; - forward->z = pcv.x * ncv.y; - } - - if(right) { - right->x = pcv.z * pcv.y; - right->y = psv.z * pcv.y; - right->z = nsv.y; - } - - if(up) { - up->x = psv.x * psv.y * pcv.z + ncv.y * psv.z; - up->y = pcv.x * pcv.z; - up->z = nsv.x * ncv.y * pcv.z + psv.y * psv.z; - } -} +#pragma once + +#include "core/math/constexpr.hh" + +constexpr float A180 = math::radians(180.0f); +constexpr float A360 = math::radians(360.0f); + +namespace math +{ +float wrap_180(float angle); +float wrap_360(float angle); +} // namespace math + +namespace math +{ +glm::fvec3 wrap_180(const glm::fvec3& angles); +glm::fvec3 wrap_360(const glm::fvec3& angles); +} // namespace math + +namespace math +{ +void vectors(const glm::fvec3& angles, glm::fvec3& forward); +void vectors(const glm::fvec3& angles, glm::fvec3* forward, glm::fvec3* right, glm::fvec3* up); +} // namespace math + +inline float math::wrap_180(float angle) +{ + const auto result = std::fmod(angle + A180, A360); + + if(result < 0.0f) { + return result + A180; + } + + return result - A180; +} + +inline float math::wrap_360(float angle) +{ + return std::fmod(std::fmod(angle, A360) + A360, A360); +} + +inline glm::fvec3 math::wrap_180(const glm::fvec3& angles) +{ + return glm::fvec3 { + math::wrap_180(angles.x), + math::wrap_180(angles.y), + math::wrap_180(angles.z), + }; +} + +inline glm::fvec3 math::wrap_360(const glm::fvec3& angles) +{ + return glm::fvec3 { + math::wrap_360(angles.x), + math::wrap_360(angles.y), + math::wrap_360(angles.z), + }; +} + +inline void math::vectors(const glm::fvec3& angles, glm::fvec3& forward) +{ + const float cosp = std::cos(angles.x); + const float cosy = std::cos(angles.y); + const float sinp = std::sin(angles.x); + const float siny = std::sin(angles.y); + + forward.x = cosp * siny * (-1.0f); + forward.y = sinp; + forward.z = cosp * cosy * (-1.0f); +} + +inline void math::vectors(const glm::fvec3& angles, glm::fvec3* forward, glm::fvec3* right, glm::fvec3* up) +{ + if(!forward && !right && !up) { + // There's no point in figuring out + // direction vectors if nothing is passed + // in the function to store that stuff in + return; + } + + const auto pcv = glm::cos(angles); + const auto psv = glm::sin(angles); + const auto ncv = pcv * (-1.0f); + const auto nsv = psv * (-1.0f); + + if(forward) { + forward->x = pcv.x * nsv.y; + forward->y = psv.x; + forward->z = pcv.x * ncv.y; + } + + if(right) { + right->x = pcv.z * pcv.y; + right->y = psv.z * pcv.y; + right->z = nsv.y; + } + + if(up) { + up->x = psv.x * psv.y * pcv.z + ncv.y * psv.z; + up->y = pcv.x * pcv.z; + up->z = nsv.x * ncv.y * pcv.z + psv.y * psv.z; + } +} diff --git a/core/math/concepts.hh b/core/math/concepts.hh index 70859c2..10cb74a 100644 --- a/core/math/concepts.hh +++ b/core/math/concepts.hh @@ -1,11 +1,11 @@ -#pragma once - -namespace math -{ -template -concept Arithmetic = std::is_arithmetic_v; -template -concept Integer = std::is_integral_v; -template -concept FloatingPoint = std::is_floating_point_v; -} // namespace math +#pragma once + +namespace math +{ +template +concept Arithmetic = std::is_arithmetic_v; +template +concept Integer = std::is_integral_v; +template +concept FloatingPoint = std::is_floating_point_v; +} // namespace math diff --git a/core/math/constexpr.hh b/core/math/constexpr.hh index 65dbbbf..e6c4b6d 100644 --- a/core/math/constexpr.hh +++ b/core/math/constexpr.hh @@ -1,198 +1,198 @@ -#pragma once - -#include "core/math/concepts.hh" - -namespace math -{ -template -constexpr static inline const T abs(const T x); -template -constexpr static inline const std::size_t array_size(const T (&)[L]); -template -constexpr static inline const T ceil(const F x); -template -constexpr static inline const T degrees(const T x); -template -constexpr static inline const T floor(const F x); -template -constexpr static inline const T clamp(const T x, const T min, const T max); -template -constexpr static inline const T lerp(const T x, const T y, const F a); -template -constexpr static inline const T log2(const T x); -template -constexpr static inline const T max(const T x, const T y); -template -constexpr static inline const T min(const T x, const T y); -template -requires std::is_signed_v -constexpr static inline const T mod_signed(const T x, const T m); -template -constexpr static inline const T pow2(const T x); -template -constexpr static inline const T radians(const T x); -template -constexpr static inline const bool range(const T x, const T min, const T max); -template -constexpr static inline const T sign(const F x); -template -constexpr static inline const T smoothstep(const T x, const T y, const F a); -} // namespace math - -template -constexpr static inline const T math::abs(const T x) -{ - if(x < static_cast(0)) { - return -x; - } - else { - return x; - } -} - -template -constexpr static inline const std::size_t math::array_size(const T (&)[L]) -{ - return L; -} - -template -constexpr static inline const T math::ceil(const F x) -{ - const T ival = static_cast(x); - - if(ival < x) { - return ival + static_cast(1); - } - else { - return ival; - } -} - -template -constexpr static inline const T math::degrees(const T x) -{ - return x * static_cast(180.0) / static_cast(M_PI); -} - -template -constexpr static inline const T math::floor(const F x) -{ - const T ival = static_cast(x); - - if(ival > x) { - return ival - static_cast(1); - } - else { - return ival; - } -} - -template -constexpr static inline const T math::clamp(const T x, const T min, const T max) -{ - if(x < min) { - return min; - } - else if(x > max) { - return max; - } - else { - return x; - } -} - -template -constexpr static inline const T math::lerp(const T x, const T y, const F a) -{ - return static_cast(static_cast(x) * (static_cast(1.0f) - a) + static_cast(y) * a); -} - -template -constexpr static inline const T math::log2(const T x) -{ - if(x < 2) { - return 0; - } - else { - return math::log2((x + 1) >> 1) + 1; - } -} - -template -constexpr static inline const T math::max(const T x, const T y) -{ - if(x < y) { - return y; - } - else { - return x; - } -} - -template -constexpr static inline const T math::min(const T x, const T y) -{ - if(x > y) { - return y; - } - else { - return x; - } -} - -template -requires std::is_signed_v -constexpr static inline const T math::mod_signed(const T x, const T m) -{ - auto result = static_cast(x % m); - - if(result < T(0)) { - return result + m; - } - else { - return result; - } -} - -template -constexpr static inline const T math::pow2(const T x) -{ - T value = static_cast(1); - while(value < x) - value *= static_cast(2); - return value; -} - -template -constexpr static inline const T math::radians(const T x) -{ - return x * static_cast(M_PI) / static_cast(180.0); -} - -template -constexpr static inline const bool math::range(const T x, const T min, const T max) -{ - return ((x >= min) && (x <= max)); -} - -template -constexpr static inline const T math::sign(const F x) -{ - if(x < F(0)) { - return T(-1); - } - else if(x > F(0)) { - return T(+1); - } - else { - return T(0); - } -} - -template -constexpr static inline const T math::smoothstep(const T x, const T y, const F a) -{ - const F t = math::clamp((a - x) / (y - x), F(0), F(1)); - return static_cast(t * t * (F(3) - F(2) * t)); -} +#pragma once + +#include "core/math/concepts.hh" + +namespace math +{ +template +constexpr static inline const T abs(const T x); +template +constexpr static inline const std::size_t array_size(const T (&)[L]); +template +constexpr static inline const T ceil(const F x); +template +constexpr static inline const T degrees(const T x); +template +constexpr static inline const T floor(const F x); +template +constexpr static inline const T clamp(const T x, const T min, const T max); +template +constexpr static inline const T lerp(const T x, const T y, const F a); +template +constexpr static inline const T log2(const T x); +template +constexpr static inline const T max(const T x, const T y); +template +constexpr static inline const T min(const T x, const T y); +template +requires std::is_signed_v +constexpr static inline const T mod_signed(const T x, const T m); +template +constexpr static inline const T pow2(const T x); +template +constexpr static inline const T radians(const T x); +template +constexpr static inline const bool range(const T x, const T min, const T max); +template +constexpr static inline const T sign(const F x); +template +constexpr static inline const T smoothstep(const T x, const T y, const F a); +} // namespace math + +template +constexpr static inline const T math::abs(const T x) +{ + if(x < static_cast(0)) { + return -x; + } + else { + return x; + } +} + +template +constexpr static inline const std::size_t math::array_size(const T (&)[L]) +{ + return L; +} + +template +constexpr static inline const T math::ceil(const F x) +{ + const T ival = static_cast(x); + + if(ival < x) { + return ival + static_cast(1); + } + else { + return ival; + } +} + +template +constexpr static inline const T math::degrees(const T x) +{ + return x * static_cast(180.0) / static_cast(M_PI); +} + +template +constexpr static inline const T math::floor(const F x) +{ + const T ival = static_cast(x); + + if(ival > x) { + return ival - static_cast(1); + } + else { + return ival; + } +} + +template +constexpr static inline const T math::clamp(const T x, const T min, const T max) +{ + if(x < min) { + return min; + } + else if(x > max) { + return max; + } + else { + return x; + } +} + +template +constexpr static inline const T math::lerp(const T x, const T y, const F a) +{ + return static_cast(static_cast(x) * (static_cast(1.0f) - a) + static_cast(y) * a); +} + +template +constexpr static inline const T math::log2(const T x) +{ + if(x < 2) { + return 0; + } + else { + return math::log2((x + 1) >> 1) + 1; + } +} + +template +constexpr static inline const T math::max(const T x, const T y) +{ + if(x < y) { + return y; + } + else { + return x; + } +} + +template +constexpr static inline const T math::min(const T x, const T y) +{ + if(x > y) { + return y; + } + else { + return x; + } +} + +template +requires std::is_signed_v +constexpr static inline const T math::mod_signed(const T x, const T m) +{ + auto result = static_cast(x % m); + + if(result < T(0)) { + return result + m; + } + else { + return result; + } +} + +template +constexpr static inline const T math::pow2(const T x) +{ + T value = static_cast(1); + while(value < x) + value *= static_cast(2); + return value; +} + +template +constexpr static inline const T math::radians(const T x) +{ + return x * static_cast(M_PI) / static_cast(180.0); +} + +template +constexpr static inline const bool math::range(const T x, const T min, const T max) +{ + return ((x >= min) && (x <= max)); +} + +template +constexpr static inline const T math::sign(const F x) +{ + if(x < F(0)) { + return T(-1); + } + else if(x > F(0)) { + return T(+1); + } + else { + return T(0); + } +} + +template +constexpr static inline const T math::smoothstep(const T x, const T y, const F a) +{ + const F t = math::clamp((a - x) / (y - x), F(0), F(1)); + return static_cast(t * t * (F(3) - F(2) * t)); +} diff --git a/core/math/crc64.cc b/core/math/crc64.cc index 4311eaf..0b6a830 100644 --- a/core/math/crc64.cc +++ b/core/math/crc64.cc @@ -1,71 +1,71 @@ -#include "core/pch.hh" - -#include "core/math/crc64.hh" - -// The lookup table for CRC64 checksum; this lookup -// table is generated using ECMA-182 compilant parameters: -// - Polynomial: `0x42F0E1EBA9EA3693` -// - Initial value: `0x0000000000000000` -// - Final xor: `0x0000000000000000` -// CRC Calculator: https://www.sunshine2k.de/coding/javascript/crc/crc_js.html -constexpr static const std::uint64_t crc_table[256] = { 0x0000000000000000, 0x42F0E1EBA9EA3693, 0x85E1C3D753D46D26, 0xC711223CFA3E5BB5, - 0x493366450E42ECDF, 0x0BC387AEA7A8DA4C, 0xCCD2A5925D9681F9, 0x8E224479F47CB76A, 0x9266CC8A1C85D9BE, 0xD0962D61B56FEF2D, - 0x17870F5D4F51B498, 0x5577EEB6E6BB820B, 0xDB55AACF12C73561, 0x99A54B24BB2D03F2, 0x5EB4691841135847, 0x1C4488F3E8F96ED4, - 0x663D78FF90E185EF, 0x24CD9914390BB37C, 0xE3DCBB28C335E8C9, 0xA12C5AC36ADFDE5A, 0x2F0E1EBA9EA36930, 0x6DFEFF5137495FA3, - 0xAAEFDD6DCD770416, 0xE81F3C86649D3285, 0xF45BB4758C645C51, 0xB6AB559E258E6AC2, 0x71BA77A2DFB03177, 0x334A9649765A07E4, - 0xBD68D2308226B08E, 0xFF9833DB2BCC861D, 0x388911E7D1F2DDA8, 0x7A79F00C7818EB3B, 0xCC7AF1FF21C30BDE, 0x8E8A101488293D4D, - 0x499B3228721766F8, 0x0B6BD3C3DBFD506B, 0x854997BA2F81E701, 0xC7B97651866BD192, 0x00A8546D7C558A27, 0x4258B586D5BFBCB4, - 0x5E1C3D753D46D260, 0x1CECDC9E94ACE4F3, 0xDBFDFEA26E92BF46, 0x990D1F49C77889D5, 0x172F5B3033043EBF, 0x55DFBADB9AEE082C, - 0x92CE98E760D05399, 0xD03E790CC93A650A, 0xAA478900B1228E31, 0xE8B768EB18C8B8A2, 0x2FA64AD7E2F6E317, 0x6D56AB3C4B1CD584, - 0xE374EF45BF6062EE, 0xA1840EAE168A547D, 0x66952C92ECB40FC8, 0x2465CD79455E395B, 0x3821458AADA7578F, 0x7AD1A461044D611C, - 0xBDC0865DFE733AA9, 0xFF3067B657990C3A, 0x711223CFA3E5BB50, 0x33E2C2240A0F8DC3, 0xF4F3E018F031D676, 0xB60301F359DBE0E5, - 0xDA050215EA6C212F, 0x98F5E3FE438617BC, 0x5FE4C1C2B9B84C09, 0x1D14202910527A9A, 0x93366450E42ECDF0, 0xD1C685BB4DC4FB63, - 0x16D7A787B7FAA0D6, 0x5427466C1E109645, 0x4863CE9FF6E9F891, 0x0A932F745F03CE02, 0xCD820D48A53D95B7, 0x8F72ECA30CD7A324, - 0x0150A8DAF8AB144E, 0x43A04931514122DD, 0x84B16B0DAB7F7968, 0xC6418AE602954FFB, 0xBC387AEA7A8DA4C0, 0xFEC89B01D3679253, - 0x39D9B93D2959C9E6, 0x7B2958D680B3FF75, 0xF50B1CAF74CF481F, 0xB7FBFD44DD257E8C, 0x70EADF78271B2539, 0x321A3E938EF113AA, - 0x2E5EB66066087D7E, 0x6CAE578BCFE24BED, 0xABBF75B735DC1058, 0xE94F945C9C3626CB, 0x676DD025684A91A1, 0x259D31CEC1A0A732, - 0xE28C13F23B9EFC87, 0xA07CF2199274CA14, 0x167FF3EACBAF2AF1, 0x548F120162451C62, 0x939E303D987B47D7, 0xD16ED1D631917144, - 0x5F4C95AFC5EDC62E, 0x1DBC74446C07F0BD, 0xDAAD56789639AB08, 0x985DB7933FD39D9B, 0x84193F60D72AF34F, 0xC6E9DE8B7EC0C5DC, - 0x01F8FCB784FE9E69, 0x43081D5C2D14A8FA, 0xCD2A5925D9681F90, 0x8FDAB8CE70822903, 0x48CB9AF28ABC72B6, 0x0A3B7B1923564425, - 0x70428B155B4EAF1E, 0x32B26AFEF2A4998D, 0xF5A348C2089AC238, 0xB753A929A170F4AB, 0x3971ED50550C43C1, 0x7B810CBBFCE67552, - 0xBC902E8706D82EE7, 0xFE60CF6CAF321874, 0xE224479F47CB76A0, 0xA0D4A674EE214033, 0x67C58448141F1B86, 0x253565A3BDF52D15, - 0xAB1721DA49899A7F, 0xE9E7C031E063ACEC, 0x2EF6E20D1A5DF759, 0x6C0603E6B3B7C1CA, 0xF6FAE5C07D3274CD, 0xB40A042BD4D8425E, - 0x731B26172EE619EB, 0x31EBC7FC870C2F78, 0xBFC9838573709812, 0xFD39626EDA9AAE81, 0x3A28405220A4F534, 0x78D8A1B9894EC3A7, - 0x649C294A61B7AD73, 0x266CC8A1C85D9BE0, 0xE17DEA9D3263C055, 0xA38D0B769B89F6C6, 0x2DAF4F0F6FF541AC, 0x6F5FAEE4C61F773F, - 0xA84E8CD83C212C8A, 0xEABE6D3395CB1A19, 0x90C79D3FEDD3F122, 0xD2377CD44439C7B1, 0x15265EE8BE079C04, 0x57D6BF0317EDAA97, - 0xD9F4FB7AE3911DFD, 0x9B041A914A7B2B6E, 0x5C1538ADB04570DB, 0x1EE5D94619AF4648, 0x02A151B5F156289C, 0x4051B05E58BC1E0F, - 0x87409262A28245BA, 0xC5B073890B687329, 0x4B9237F0FF14C443, 0x0962D61B56FEF2D0, 0xCE73F427ACC0A965, 0x8C8315CC052A9FF6, - 0x3A80143F5CF17F13, 0x7870F5D4F51B4980, 0xBF61D7E80F251235, 0xFD913603A6CF24A6, 0x73B3727A52B393CC, 0x31439391FB59A55F, - 0xF652B1AD0167FEEA, 0xB4A25046A88DC879, 0xA8E6D8B54074A6AD, 0xEA16395EE99E903E, 0x2D071B6213A0CB8B, 0x6FF7FA89BA4AFD18, - 0xE1D5BEF04E364A72, 0xA3255F1BE7DC7CE1, 0x64347D271DE22754, 0x26C49CCCB40811C7, 0x5CBD6CC0CC10FAFC, 0x1E4D8D2B65FACC6F, - 0xD95CAF179FC497DA, 0x9BAC4EFC362EA149, 0x158E0A85C2521623, 0x577EEB6E6BB820B0, 0x906FC95291867B05, 0xD29F28B9386C4D96, - 0xCEDBA04AD0952342, 0x8C2B41A1797F15D1, 0x4B3A639D83414E64, 0x09CA82762AAB78F7, 0x87E8C60FDED7CF9D, 0xC51827E4773DF90E, - 0x020905D88D03A2BB, 0x40F9E43324E99428, 0x2CFFE7D5975E55E2, 0x6E0F063E3EB46371, 0xA91E2402C48A38C4, 0xEBEEC5E96D600E57, - 0x65CC8190991CB93D, 0x273C607B30F68FAE, 0xE02D4247CAC8D41B, 0xA2DDA3AC6322E288, 0xBE992B5F8BDB8C5C, 0xFC69CAB42231BACF, - 0x3B78E888D80FE17A, 0x7988096371E5D7E9, 0xF7AA4D1A85996083, 0xB55AACF12C735610, 0x724B8ECDD64D0DA5, 0x30BB6F267FA73B36, - 0x4AC29F2A07BFD00D, 0x08327EC1AE55E69E, 0xCF235CFD546BBD2B, 0x8DD3BD16FD818BB8, 0x03F1F96F09FD3CD2, 0x41011884A0170A41, - 0x86103AB85A2951F4, 0xC4E0DB53F3C36767, 0xD8A453A01B3A09B3, 0x9A54B24BB2D03F20, 0x5D45907748EE6495, 0x1FB5719CE1045206, - 0x919735E51578E56C, 0xD367D40EBC92D3FF, 0x1476F63246AC884A, 0x568617D9EF46BED9, 0xE085162AB69D5E3C, 0xA275F7C11F7768AF, - 0x6564D5FDE549331A, 0x279434164CA30589, 0xA9B6706FB8DFB2E3, 0xEB46918411358470, 0x2C57B3B8EB0BDFC5, 0x6EA7525342E1E956, - 0x72E3DAA0AA188782, 0x30133B4B03F2B111, 0xF7021977F9CCEAA4, 0xB5F2F89C5026DC37, 0x3BD0BCE5A45A6B5D, 0x79205D0E0DB05DCE, - 0xBE317F32F78E067B, 0xFCC19ED95E6430E8, 0x86B86ED5267CDBD3, 0xC4488F3E8F96ED40, 0x0359AD0275A8B6F5, 0x41A94CE9DC428066, - 0xCF8B0890283E370C, 0x8D7BE97B81D4019F, 0x4A6ACB477BEA5A2A, 0x089A2AACD2006CB9, 0x14DEA25F3AF9026D, 0x562E43B4931334FE, - 0x913F6188692D6F4B, 0xD3CF8063C0C759D8, 0x5DEDC41A34BBEEB2, 0x1F1D25F19D51D821, 0xD80C07CD676F8394, 0x9AFCE626CE85B507 }; - -std::uint64_t math::crc64(const void* buffer, std::size_t size, std::uint64_t combine) -{ - auto data = reinterpret_cast(buffer); - for(std::size_t i = 0; i < size; ++i) - combine = crc_table[((combine >> 56) ^ data[i]) & 0xFF] ^ (combine << 8); - return combine; -} - -std::uint64_t math::crc64(const std::vector& buffer, std::uint64_t combine) -{ - return math::crc64(buffer.data(), buffer.size(), combine); -} - -std::uint64_t math::crc64(const std::string& buffer, std::uint64_t combine) -{ - return math::crc64(buffer.data(), buffer.size(), combine); -} +#include "core/pch.hh" + +#include "core/math/crc64.hh" + +// The lookup table for CRC64 checksum; this lookup +// table is generated using ECMA-182 compilant parameters: +// - Polynomial: `0x42F0E1EBA9EA3693` +// - Initial value: `0x0000000000000000` +// - Final xor: `0x0000000000000000` +// CRC Calculator: https://www.sunshine2k.de/coding/javascript/crc/crc_js.html +constexpr static const std::uint64_t crc_table[256] = { 0x0000000000000000, 0x42F0E1EBA9EA3693, 0x85E1C3D753D46D26, 0xC711223CFA3E5BB5, + 0x493366450E42ECDF, 0x0BC387AEA7A8DA4C, 0xCCD2A5925D9681F9, 0x8E224479F47CB76A, 0x9266CC8A1C85D9BE, 0xD0962D61B56FEF2D, + 0x17870F5D4F51B498, 0x5577EEB6E6BB820B, 0xDB55AACF12C73561, 0x99A54B24BB2D03F2, 0x5EB4691841135847, 0x1C4488F3E8F96ED4, + 0x663D78FF90E185EF, 0x24CD9914390BB37C, 0xE3DCBB28C335E8C9, 0xA12C5AC36ADFDE5A, 0x2F0E1EBA9EA36930, 0x6DFEFF5137495FA3, + 0xAAEFDD6DCD770416, 0xE81F3C86649D3285, 0xF45BB4758C645C51, 0xB6AB559E258E6AC2, 0x71BA77A2DFB03177, 0x334A9649765A07E4, + 0xBD68D2308226B08E, 0xFF9833DB2BCC861D, 0x388911E7D1F2DDA8, 0x7A79F00C7818EB3B, 0xCC7AF1FF21C30BDE, 0x8E8A101488293D4D, + 0x499B3228721766F8, 0x0B6BD3C3DBFD506B, 0x854997BA2F81E701, 0xC7B97651866BD192, 0x00A8546D7C558A27, 0x4258B586D5BFBCB4, + 0x5E1C3D753D46D260, 0x1CECDC9E94ACE4F3, 0xDBFDFEA26E92BF46, 0x990D1F49C77889D5, 0x172F5B3033043EBF, 0x55DFBADB9AEE082C, + 0x92CE98E760D05399, 0xD03E790CC93A650A, 0xAA478900B1228E31, 0xE8B768EB18C8B8A2, 0x2FA64AD7E2F6E317, 0x6D56AB3C4B1CD584, + 0xE374EF45BF6062EE, 0xA1840EAE168A547D, 0x66952C92ECB40FC8, 0x2465CD79455E395B, 0x3821458AADA7578F, 0x7AD1A461044D611C, + 0xBDC0865DFE733AA9, 0xFF3067B657990C3A, 0x711223CFA3E5BB50, 0x33E2C2240A0F8DC3, 0xF4F3E018F031D676, 0xB60301F359DBE0E5, + 0xDA050215EA6C212F, 0x98F5E3FE438617BC, 0x5FE4C1C2B9B84C09, 0x1D14202910527A9A, 0x93366450E42ECDF0, 0xD1C685BB4DC4FB63, + 0x16D7A787B7FAA0D6, 0x5427466C1E109645, 0x4863CE9FF6E9F891, 0x0A932F745F03CE02, 0xCD820D48A53D95B7, 0x8F72ECA30CD7A324, + 0x0150A8DAF8AB144E, 0x43A04931514122DD, 0x84B16B0DAB7F7968, 0xC6418AE602954FFB, 0xBC387AEA7A8DA4C0, 0xFEC89B01D3679253, + 0x39D9B93D2959C9E6, 0x7B2958D680B3FF75, 0xF50B1CAF74CF481F, 0xB7FBFD44DD257E8C, 0x70EADF78271B2539, 0x321A3E938EF113AA, + 0x2E5EB66066087D7E, 0x6CAE578BCFE24BED, 0xABBF75B735DC1058, 0xE94F945C9C3626CB, 0x676DD025684A91A1, 0x259D31CEC1A0A732, + 0xE28C13F23B9EFC87, 0xA07CF2199274CA14, 0x167FF3EACBAF2AF1, 0x548F120162451C62, 0x939E303D987B47D7, 0xD16ED1D631917144, + 0x5F4C95AFC5EDC62E, 0x1DBC74446C07F0BD, 0xDAAD56789639AB08, 0x985DB7933FD39D9B, 0x84193F60D72AF34F, 0xC6E9DE8B7EC0C5DC, + 0x01F8FCB784FE9E69, 0x43081D5C2D14A8FA, 0xCD2A5925D9681F90, 0x8FDAB8CE70822903, 0x48CB9AF28ABC72B6, 0x0A3B7B1923564425, + 0x70428B155B4EAF1E, 0x32B26AFEF2A4998D, 0xF5A348C2089AC238, 0xB753A929A170F4AB, 0x3971ED50550C43C1, 0x7B810CBBFCE67552, + 0xBC902E8706D82EE7, 0xFE60CF6CAF321874, 0xE224479F47CB76A0, 0xA0D4A674EE214033, 0x67C58448141F1B86, 0x253565A3BDF52D15, + 0xAB1721DA49899A7F, 0xE9E7C031E063ACEC, 0x2EF6E20D1A5DF759, 0x6C0603E6B3B7C1CA, 0xF6FAE5C07D3274CD, 0xB40A042BD4D8425E, + 0x731B26172EE619EB, 0x31EBC7FC870C2F78, 0xBFC9838573709812, 0xFD39626EDA9AAE81, 0x3A28405220A4F534, 0x78D8A1B9894EC3A7, + 0x649C294A61B7AD73, 0x266CC8A1C85D9BE0, 0xE17DEA9D3263C055, 0xA38D0B769B89F6C6, 0x2DAF4F0F6FF541AC, 0x6F5FAEE4C61F773F, + 0xA84E8CD83C212C8A, 0xEABE6D3395CB1A19, 0x90C79D3FEDD3F122, 0xD2377CD44439C7B1, 0x15265EE8BE079C04, 0x57D6BF0317EDAA97, + 0xD9F4FB7AE3911DFD, 0x9B041A914A7B2B6E, 0x5C1538ADB04570DB, 0x1EE5D94619AF4648, 0x02A151B5F156289C, 0x4051B05E58BC1E0F, + 0x87409262A28245BA, 0xC5B073890B687329, 0x4B9237F0FF14C443, 0x0962D61B56FEF2D0, 0xCE73F427ACC0A965, 0x8C8315CC052A9FF6, + 0x3A80143F5CF17F13, 0x7870F5D4F51B4980, 0xBF61D7E80F251235, 0xFD913603A6CF24A6, 0x73B3727A52B393CC, 0x31439391FB59A55F, + 0xF652B1AD0167FEEA, 0xB4A25046A88DC879, 0xA8E6D8B54074A6AD, 0xEA16395EE99E903E, 0x2D071B6213A0CB8B, 0x6FF7FA89BA4AFD18, + 0xE1D5BEF04E364A72, 0xA3255F1BE7DC7CE1, 0x64347D271DE22754, 0x26C49CCCB40811C7, 0x5CBD6CC0CC10FAFC, 0x1E4D8D2B65FACC6F, + 0xD95CAF179FC497DA, 0x9BAC4EFC362EA149, 0x158E0A85C2521623, 0x577EEB6E6BB820B0, 0x906FC95291867B05, 0xD29F28B9386C4D96, + 0xCEDBA04AD0952342, 0x8C2B41A1797F15D1, 0x4B3A639D83414E64, 0x09CA82762AAB78F7, 0x87E8C60FDED7CF9D, 0xC51827E4773DF90E, + 0x020905D88D03A2BB, 0x40F9E43324E99428, 0x2CFFE7D5975E55E2, 0x6E0F063E3EB46371, 0xA91E2402C48A38C4, 0xEBEEC5E96D600E57, + 0x65CC8190991CB93D, 0x273C607B30F68FAE, 0xE02D4247CAC8D41B, 0xA2DDA3AC6322E288, 0xBE992B5F8BDB8C5C, 0xFC69CAB42231BACF, + 0x3B78E888D80FE17A, 0x7988096371E5D7E9, 0xF7AA4D1A85996083, 0xB55AACF12C735610, 0x724B8ECDD64D0DA5, 0x30BB6F267FA73B36, + 0x4AC29F2A07BFD00D, 0x08327EC1AE55E69E, 0xCF235CFD546BBD2B, 0x8DD3BD16FD818BB8, 0x03F1F96F09FD3CD2, 0x41011884A0170A41, + 0x86103AB85A2951F4, 0xC4E0DB53F3C36767, 0xD8A453A01B3A09B3, 0x9A54B24BB2D03F20, 0x5D45907748EE6495, 0x1FB5719CE1045206, + 0x919735E51578E56C, 0xD367D40EBC92D3FF, 0x1476F63246AC884A, 0x568617D9EF46BED9, 0xE085162AB69D5E3C, 0xA275F7C11F7768AF, + 0x6564D5FDE549331A, 0x279434164CA30589, 0xA9B6706FB8DFB2E3, 0xEB46918411358470, 0x2C57B3B8EB0BDFC5, 0x6EA7525342E1E956, + 0x72E3DAA0AA188782, 0x30133B4B03F2B111, 0xF7021977F9CCEAA4, 0xB5F2F89C5026DC37, 0x3BD0BCE5A45A6B5D, 0x79205D0E0DB05DCE, + 0xBE317F32F78E067B, 0xFCC19ED95E6430E8, 0x86B86ED5267CDBD3, 0xC4488F3E8F96ED40, 0x0359AD0275A8B6F5, 0x41A94CE9DC428066, + 0xCF8B0890283E370C, 0x8D7BE97B81D4019F, 0x4A6ACB477BEA5A2A, 0x089A2AACD2006CB9, 0x14DEA25F3AF9026D, 0x562E43B4931334FE, + 0x913F6188692D6F4B, 0xD3CF8063C0C759D8, 0x5DEDC41A34BBEEB2, 0x1F1D25F19D51D821, 0xD80C07CD676F8394, 0x9AFCE626CE85B507 }; + +std::uint64_t math::crc64(const void* buffer, std::size_t size, std::uint64_t combine) +{ + auto data = reinterpret_cast(buffer); + for(std::size_t i = 0; i < size; ++i) + combine = crc_table[((combine >> 56) ^ data[i]) & 0xFF] ^ (combine << 8); + return combine; +} + +std::uint64_t math::crc64(const std::vector& buffer, std::uint64_t combine) +{ + return math::crc64(buffer.data(), buffer.size(), combine); +} + +std::uint64_t math::crc64(const std::string& buffer, std::uint64_t combine) +{ + return math::crc64(buffer.data(), buffer.size(), combine); +} diff --git a/core/math/crc64.hh b/core/math/crc64.hh index 4dc484d..f68c951 100644 --- a/core/math/crc64.hh +++ b/core/math/crc64.hh @@ -1,8 +1,8 @@ -#pragma once - -namespace math -{ -std::uint64_t crc64(const void* buffer, std::size_t size, std::uint64_t combine = UINT64_C(0)); -std::uint64_t crc64(const std::vector& buffer, std::uint64_t combine = UINT64_C(0)); -std::uint64_t crc64(const std::string& buffer, std::uint64_t combine = UINT64_C(0)); -} // namespace math +#pragma once + +namespace math +{ +std::uint64_t crc64(const void* buffer, std::size_t size, std::uint64_t combine = UINT64_C(0)); +std::uint64_t crc64(const std::vector& buffer, std::uint64_t combine = UINT64_C(0)); +std::uint64_t crc64(const std::string& buffer, std::uint64_t combine = UINT64_C(0)); +} // namespace math diff --git a/core/math/randomizer.hh b/core/math/randomizer.hh index 04665f9..db21c95 100644 --- a/core/math/randomizer.hh +++ b/core/math/randomizer.hh @@ -1,56 +1,56 @@ -#pragma once - -namespace math -{ -template -class Randomizer final { -public: - explicit Randomizer(void); - explicit Randomizer(std::uint64_t seed); - virtual ~Randomizer(void) = default; - void add(const T& value); - const T& get(void); - void clear(void); - -private: - std::vector m_vector; - std::mt19937_64 m_twister; - std::uniform_int_distribution m_dist; -}; -} // namespace math - -template -inline math::Randomizer::Randomizer(void) -{ - m_vector.clear(); - m_twister.seed(std::random_device()()); - m_dist = std::uniform_int_distribution(0, 0); -} - -template -inline math::Randomizer::Randomizer(std::uint64_t seed) -{ - m_vector.clear(); - m_twister.seed(seed); - m_dist = std::uniform_int_distribution(0, 0); -} - -template -inline void math::Randomizer::add(const T& value) -{ - m_vector.push_back(value); - m_dist = std::uniform_int_distribution(0, m_vector.size() - 1); -} - -template -inline const T& math::Randomizer::get(void) -{ - return m_vector.at(m_dist(m_twister)); -} - -template -inline void math::Randomizer::clear(void) -{ - m_vector.clear(); - m_dist = std::uniform_int_distribution(0, 0); -} +#pragma once + +namespace math +{ +template +class Randomizer final { +public: + explicit Randomizer(void); + explicit Randomizer(std::uint64_t seed); + virtual ~Randomizer(void) = default; + void add(const T& value); + const T& get(void); + void clear(void); + +private: + std::vector m_vector; + std::mt19937_64 m_twister; + std::uniform_int_distribution m_dist; +}; +} // namespace math + +template +inline math::Randomizer::Randomizer(void) +{ + m_vector.clear(); + m_twister.seed(std::random_device()()); + m_dist = std::uniform_int_distribution(0, 0); +} + +template +inline math::Randomizer::Randomizer(std::uint64_t seed) +{ + m_vector.clear(); + m_twister.seed(seed); + m_dist = std::uniform_int_distribution(0, 0); +} + +template +inline void math::Randomizer::add(const T& value) +{ + m_vector.push_back(value); + m_dist = std::uniform_int_distribution(0, m_vector.size() - 1); +} + +template +inline const T& math::Randomizer::get(void) +{ + return m_vector.at(m_dist(m_twister)); +} + +template +inline void math::Randomizer::clear(void) +{ + m_vector.clear(); + m_dist = std::uniform_int_distribution(0, 0); +} diff --git a/core/math/vectors.hh b/core/math/vectors.hh index 73c9ab0..9b9e762 100644 --- a/core/math/vectors.hh +++ b/core/math/vectors.hh @@ -1,43 +1,43 @@ -#pragma once - -#include "core/math/concepts.hh" - -// core/vectors.hh - because NO ONE would POSSIBLY -// need integer-based distance calculations in a -// game about voxels. That would be INSANE! :D - -namespace math -{ -template -constexpr static inline const T length2(const glm::vec<2, T>& vector); -template -constexpr static inline const T length2(const glm::vec<3, T>& vector); -template -constexpr static inline const T distance2(const glm::vec<2, T>& vector_a, const glm::vec<2, T>& vector_b); -template -constexpr static inline const T distance2(const glm::vec<3, T>& vector_a, const glm::vec<3, T>& vector_b); -} // namespace math - -template -constexpr static inline const T math::length2(const glm::vec<2, T>& vector) -{ - return (vector.x * vector.x) + (vector.y * vector.y); -} - -template -constexpr static inline const T math::length2(const glm::vec<3, T>& vector) -{ - return (vector.x * vector.x) + (vector.y * vector.y) + (vector.z * vector.z); -} - -template -constexpr static inline const T math::distance2(const glm::vec<2, T>& vector_a, const glm::vec<2, T>& vector_b) -{ - return math::length2(vector_a - vector_b); -} - -template -constexpr static inline const T math::distance2(const glm::vec<3, T>& vector_a, const glm::vec<3, T>& vector_b) -{ - return math::length2(vector_a - vector_b); -} +#pragma once + +#include "core/math/concepts.hh" + +// core/vectors.hh - because NO ONE would POSSIBLY +// need integer-based distance calculations in a +// game about voxels. That would be INSANE! :D + +namespace math +{ +template +constexpr static inline const T length2(const glm::vec<2, T>& vector); +template +constexpr static inline const T length2(const glm::vec<3, T>& vector); +template +constexpr static inline const T distance2(const glm::vec<2, T>& vector_a, const glm::vec<2, T>& vector_b); +template +constexpr static inline const T distance2(const glm::vec<3, T>& vector_a, const glm::vec<3, T>& vector_b); +} // namespace math + +template +constexpr static inline const T math::length2(const glm::vec<2, T>& vector) +{ + return (vector.x * vector.x) + (vector.y * vector.y); +} + +template +constexpr static inline const T math::length2(const glm::vec<3, T>& vector) +{ + return (vector.x * vector.x) + (vector.y * vector.y) + (vector.z * vector.z); +} + +template +constexpr static inline const T math::distance2(const glm::vec<2, T>& vector_a, const glm::vec<2, T>& vector_b) +{ + return math::length2(vector_a - vector_b); +} + +template +constexpr static inline const T math::distance2(const glm::vec<3, T>& vector_a, const glm::vec<3, T>& vector_b) +{ + return math::length2(vector_a - vector_b); +} diff --git a/core/pch.hh b/core/pch.hh index 17417a5..410b819 100644 --- a/core/pch.hh +++ b/core/pch.hh @@ -1,49 +1,49 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#include - -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include - -#include - -#include -#include +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include + +#include +#include diff --git a/core/resource/image.cc b/core/resource/image.cc index d5e256d..45fe96e 100644 --- a/core/resource/image.cc +++ b/core/resource/image.cc @@ -1,81 +1,81 @@ -#include "core/pch.hh" - -#include "core/resource/image.hh" - -#include "core/resource/resource.hh" - -#include "core/utils/physfs.hh" - -static int stbi_physfs_read(void* context, char* data, int size) -{ - return PHYSFS_readBytes(reinterpret_cast(context), data, size); -} - -static void stbi_physfs_skip(void* context, int count) -{ - auto file = reinterpret_cast(context); - PHYSFS_seek(file, PHYSFS_tell(file) + count); -} - -static int stbi_physfs_eof(void* context) -{ - return PHYSFS_eof(reinterpret_cast(context)); -} - -static const void* image_load_func(const char* name, std::uint32_t flags) -{ - assert(name); - - stbi_io_callbacks callbacks; - callbacks.read = &stbi_physfs_read; - callbacks.skip = &stbi_physfs_skip; - callbacks.eof = &stbi_physfs_eof; - - stbi_set_flip_vertically_on_load(bool(flags & IMAGE_LOAD_FLIP)); - - auto file = PHYSFS_openRead(name); - - if(file == nullptr) { - spdlog::error("image: {}: {}", name, utils::physfs_error()); - return nullptr; - } - - int desired_channels; - - if(flags & IMAGE_LOAD_GRAY) { - desired_channels = STBI_grey; - } - else { - desired_channels = STBI_rgb_alpha; - } - - int width, height, channels; - auto pixels = stbi_load_from_callbacks(&callbacks, file, &width, &height, &channels, desired_channels); - - PHYSFS_close(file); - - if(pixels == nullptr) { - spdlog::error("image: {}: {}", name, stbi_failure_reason()); - return nullptr; - } - - auto image = new Image; - image->pixels = pixels; - image->size = glm::ivec2(width, height); - return image; -} - -static void image_free_func(const void* resource) -{ - assert(resource); - - auto image = reinterpret_cast(resource); - stbi_image_free(image->pixels); - - delete image; -} - -void Image::register_resource(void) -{ - resource::register_loader(&image_load_func, &image_free_func); -} +#include "core/pch.hh" + +#include "core/resource/image.hh" + +#include "core/resource/resource.hh" + +#include "core/utils/physfs.hh" + +static int stbi_physfs_read(void* context, char* data, int size) +{ + return PHYSFS_readBytes(reinterpret_cast(context), data, size); +} + +static void stbi_physfs_skip(void* context, int count) +{ + auto file = reinterpret_cast(context); + PHYSFS_seek(file, PHYSFS_tell(file) + count); +} + +static int stbi_physfs_eof(void* context) +{ + return PHYSFS_eof(reinterpret_cast(context)); +} + +static const void* image_load_func(const char* name, std::uint32_t flags) +{ + assert(name); + + stbi_io_callbacks callbacks; + callbacks.read = &stbi_physfs_read; + callbacks.skip = &stbi_physfs_skip; + callbacks.eof = &stbi_physfs_eof; + + stbi_set_flip_vertically_on_load(bool(flags & IMAGE_LOAD_FLIP)); + + auto file = PHYSFS_openRead(name); + + if(file == nullptr) { + spdlog::error("image: {}: {}", name, utils::physfs_error()); + return nullptr; + } + + int desired_channels; + + if(flags & IMAGE_LOAD_GRAY) { + desired_channels = STBI_grey; + } + else { + desired_channels = STBI_rgb_alpha; + } + + int width, height, channels; + auto pixels = stbi_load_from_callbacks(&callbacks, file, &width, &height, &channels, desired_channels); + + PHYSFS_close(file); + + if(pixels == nullptr) { + spdlog::error("image: {}: {}", name, stbi_failure_reason()); + return nullptr; + } + + auto image = new Image; + image->pixels = pixels; + image->size = glm::ivec2(width, height); + return image; +} + +static void image_free_func(const void* resource) +{ + assert(resource); + + auto image = reinterpret_cast(resource); + stbi_image_free(image->pixels); + + delete image; +} + +void Image::register_resource(void) +{ + resource::register_loader(&image_load_func, &image_free_func); +} diff --git a/core/resource/image.hh b/core/resource/image.hh index 575591f..8867b97 100644 --- a/core/resource/image.hh +++ b/core/resource/image.hh @@ -1,11 +1,11 @@ -#pragma once - -constexpr static unsigned int IMAGE_LOAD_GRAY = 0x0001U; -constexpr static unsigned int IMAGE_LOAD_FLIP = 0x0002U; - -struct Image final { - static void register_resource(void); - - stbi_uc* pixels; - glm::ivec2 size; -}; +#pragma once + +constexpr static unsigned int IMAGE_LOAD_GRAY = 0x0001U; +constexpr static unsigned int IMAGE_LOAD_FLIP = 0x0002U; + +struct Image final { + static void register_resource(void); + + stbi_uc* pixels; + glm::ivec2 size; +}; diff --git a/core/resource/resource.cc b/core/resource/resource.cc index 600843f..21d1e4e 100644 --- a/core/resource/resource.cc +++ b/core/resource/resource.cc @@ -1,129 +1,129 @@ -#include "core/pch.hh" - -#include "core/resource/resource.hh" - -struct ResourceLoader final { - ResourceLoadFunc load_func; - ResourceFreeFunc free_func; - emhash8::HashMap> resources; - std::vector> cache; - std::string class_name; -}; - -namespace -{ -emhash8::HashMap> loaders; -} // namespace - -void resource::detail::register_loader(const std::type_info& type, ResourceLoadFunc load_func, ResourceFreeFunc free_func) -{ - assert(load_func); - assert(free_func); - - auto type_index = std::type_index(type); - auto loader = std::make_unique(); - loader->class_name = type.name(); - loader->load_func = load_func; - loader->free_func = free_func; - - assert(!loaders.contains(type_index)); - - loaders.insert_or_assign(type_index, std::move(loader)); -} - -std::shared_ptr resource::detail::load_resource(const std::type_info& type, std::string_view name, std::uint32_t flags) -{ - auto name_str = std::string(name); - auto type_index = std::type_index(type); - auto loader = loaders.find(type_index); - - if(loader == loaders.cend()) { - spdlog::error("resource: no loader registered for type [{}]", type.name()); - return nullptr; - } - - auto resource_it = loader->second->resources.find(name_str); - - if(resource_it == loader->second->resources.cend()) { - auto resource_raw = loader->second->load_func(name_str.c_str(), flags); - - if(resource_raw == nullptr) { - spdlog::error("resource: {} [{}]: load failed", loader->second->class_name, name); - return nullptr; - } - - std::shared_ptr resource_ptr(resource_raw, [](const void* ptr) { /* empty */ }); - auto loaded_it = loader->second->resources.insert_or_assign(name_str, std::move(resource_ptr)); - - if(flags & RESOURCE_CACHE) { - loader->second->cache.push_back(loaded_it.first->second); - } - - return loaded_it.first->second; - } - - return resource_it->second; -} - -std::shared_ptr resource::detail::find_resource(const std::type_info& type, std::string_view name) -{ - auto name_str = std::string(name); - auto type_index = std::type_index(type); - auto loader = loaders.find(type_index); - - if(loader == loaders.cend()) { - spdlog::error("resource: no loader registered for type [{}]", type.name()); - return nullptr; - } - - auto resource_it = loader->second->resources.find(name_str); - - if(resource_it == loader->second->resources.cend()) { - spdlog::error("resource: {} [{}]: not found", loader->second->class_name, name); - return nullptr; - } - - return resource_it->second; -} - -void resource::hard_cleanup(void) -{ - for(auto& [type_index, loader] : loaders) { - loader->cache.clear(); - - for(auto& [name, resource_ptr] : loader->resources) { - if(resource_ptr.use_count() > 1) { - spdlog::warn("resource: zombie resource: {} [{}] [use_count={}]", name, loader->class_name, resource_ptr.use_count()); - } - else { - spdlog::debug("resource: releasing {} [{}]", name, loader->class_name); - } - - loader->free_func(resource_ptr.get()); - } - - loader->resources.clear(); - } - - loaders.clear(); -} - -void resource::soft_cleanup(void) -{ - for(auto& [type_index, loader] : loaders) { - auto resource_it = loader->resources.begin(); - - while(resource_it != loader->resources.end()) { - if(resource_it->second.use_count() <= 1) { - spdlog::debug("resource: releasing {} [{}]", resource_it->first, loader->class_name); - - loader->free_func(resource_it->second.get()); - resource_it = loader->resources.erase(resource_it); - - continue; - } - - resource_it = std::next(resource_it); - } - } -} +#include "core/pch.hh" + +#include "core/resource/resource.hh" + +struct ResourceLoader final { + ResourceLoadFunc load_func; + ResourceFreeFunc free_func; + emhash8::HashMap> resources; + std::vector> cache; + std::string class_name; +}; + +namespace +{ +emhash8::HashMap> loaders; +} // namespace + +void resource::detail::register_loader(const std::type_info& type, ResourceLoadFunc load_func, ResourceFreeFunc free_func) +{ + assert(load_func); + assert(free_func); + + auto type_index = std::type_index(type); + auto loader = std::make_unique(); + loader->class_name = type.name(); + loader->load_func = load_func; + loader->free_func = free_func; + + assert(!loaders.contains(type_index)); + + loaders.insert_or_assign(type_index, std::move(loader)); +} + +std::shared_ptr resource::detail::load_resource(const std::type_info& type, std::string_view name, std::uint32_t flags) +{ + auto name_str = std::string(name); + auto type_index = std::type_index(type); + auto loader = loaders.find(type_index); + + if(loader == loaders.cend()) { + spdlog::error("resource: no loader registered for type [{}]", type.name()); + return nullptr; + } + + auto resource_it = loader->second->resources.find(name_str); + + if(resource_it == loader->second->resources.cend()) { + auto resource_raw = loader->second->load_func(name_str.c_str(), flags); + + if(resource_raw == nullptr) { + spdlog::error("resource: {} [{}]: load failed", loader->second->class_name, name); + return nullptr; + } + + std::shared_ptr resource_ptr(resource_raw, [](const void* ptr) { /* empty */ }); + auto loaded_it = loader->second->resources.insert_or_assign(name_str, std::move(resource_ptr)); + + if(flags & RESOURCE_CACHE) { + loader->second->cache.push_back(loaded_it.first->second); + } + + return loaded_it.first->second; + } + + return resource_it->second; +} + +std::shared_ptr resource::detail::find_resource(const std::type_info& type, std::string_view name) +{ + auto name_str = std::string(name); + auto type_index = std::type_index(type); + auto loader = loaders.find(type_index); + + if(loader == loaders.cend()) { + spdlog::error("resource: no loader registered for type [{}]", type.name()); + return nullptr; + } + + auto resource_it = loader->second->resources.find(name_str); + + if(resource_it == loader->second->resources.cend()) { + spdlog::error("resource: {} [{}]: not found", loader->second->class_name, name); + return nullptr; + } + + return resource_it->second; +} + +void resource::hard_cleanup(void) +{ + for(auto& [type_index, loader] : loaders) { + loader->cache.clear(); + + for(auto& [name, resource_ptr] : loader->resources) { + if(resource_ptr.use_count() > 1) { + spdlog::warn("resource: zombie resource: {} [{}] [use_count={}]", name, loader->class_name, resource_ptr.use_count()); + } + else { + spdlog::debug("resource: releasing {} [{}]", name, loader->class_name); + } + + loader->free_func(resource_ptr.get()); + } + + loader->resources.clear(); + } + + loaders.clear(); +} + +void resource::soft_cleanup(void) +{ + for(auto& [type_index, loader] : loaders) { + auto resource_it = loader->resources.begin(); + + while(resource_it != loader->resources.end()) { + if(resource_it->second.use_count() <= 1) { + spdlog::debug("resource: releasing {} [{}]", resource_it->first, loader->class_name); + + loader->free_func(resource_it->second.get()); + resource_it = loader->resources.erase(resource_it); + + continue; + } + + resource_it = std::next(resource_it); + } + } +} diff --git a/core/resource/resource.hh b/core/resource/resource.hh index 105c7ff..fbca130 100644 --- a/core/resource/resource.hh +++ b/core/resource/resource.hh @@ -1,53 +1,53 @@ -#pragma once - -template -using resource_ptr = std::shared_ptr; - -constexpr std::uint32_t RESOURCE_CACHE = 0x00000001U; ///< Cache the resource after loading -constexpr std::uint32_t RESOURCE_USER = 0xFFFFFF00U; ///< User-defined flags for custom behavior - -using ResourceLoadFunc = const void* (*)(const char* name, std::uint32_t flags); -using ResourceFreeFunc = void (*)(const void* resource); - -namespace resource::detail -{ -void register_loader(const std::type_info& type, ResourceLoadFunc load_func, ResourceFreeFunc free_func); -resource_ptr load_resource(const std::type_info& type, std::string_view name, std::uint32_t flags); -resource_ptr find_resource(const std::type_info& type, std::string_view name); -} // namespace resource::detail - -namespace resource -{ -template -void register_loader(ResourceLoadFunc load_func, ResourceFreeFunc free_func); -template -resource_ptr load(std::string_view name, std::uint32_t flags = 0U); -template -resource_ptr find(std::string_view name); -} // namespace resource - -namespace resource -{ -void hard_cleanup(void); -void soft_cleanup(void); -} // namespace resource - -template -void resource::register_loader(ResourceLoadFunc load_func, ResourceFreeFunc free_func) -{ - resource::detail::register_loader(typeid(T), load_func, free_func); -} - -template -resource_ptr resource::load(std::string_view name, std::uint32_t flags) -{ - auto result = resource::detail::load_resource(typeid(T), name, flags); - return std::reinterpret_pointer_cast(result); -} - -template -resource_ptr resource::find(std::string_view name) -{ - auto result = resource::detail::find_resource(typeid(T), name); - return std::reinterpret_pointer_cast(result); -} +#pragma once + +template +using resource_ptr = std::shared_ptr; + +constexpr std::uint32_t RESOURCE_CACHE = 0x00000001U; ///< Cache the resource after loading +constexpr std::uint32_t RESOURCE_USER = 0xFFFFFF00U; ///< User-defined flags for custom behavior + +using ResourceLoadFunc = const void* (*)(const char* name, std::uint32_t flags); +using ResourceFreeFunc = void (*)(const void* resource); + +namespace resource::detail +{ +void register_loader(const std::type_info& type, ResourceLoadFunc load_func, ResourceFreeFunc free_func); +resource_ptr load_resource(const std::type_info& type, std::string_view name, std::uint32_t flags); +resource_ptr find_resource(const std::type_info& type, std::string_view name); +} // namespace resource::detail + +namespace resource +{ +template +void register_loader(ResourceLoadFunc load_func, ResourceFreeFunc free_func); +template +resource_ptr load(std::string_view name, std::uint32_t flags = 0U); +template +resource_ptr find(std::string_view name); +} // namespace resource + +namespace resource +{ +void hard_cleanup(void); +void soft_cleanup(void); +} // namespace resource + +template +void resource::register_loader(ResourceLoadFunc load_func, ResourceFreeFunc free_func) +{ + resource::detail::register_loader(typeid(T), load_func, free_func); +} + +template +resource_ptr resource::load(std::string_view name, std::uint32_t flags) +{ + auto result = resource::detail::load_resource(typeid(T), name, flags); + return std::reinterpret_pointer_cast(result); +} + +template +resource_ptr resource::find(std::string_view name) +{ + auto result = resource::detail::find_resource(typeid(T), name); + return std::reinterpret_pointer_cast(result); +} diff --git a/core/threading.cc b/core/threading.cc index 641e634..dcbdb9a 100644 --- a/core/threading.cc +++ b/core/threading.cc @@ -1,128 +1,128 @@ -#include "core/pch.hh" - -#include "core/threading.hh" - -#include "core/io/cmdline.hh" - -#include "core/math/constexpr.hh" - -constexpr static std::string_view DEFAULT_POOL_SIZE_ARG = "4"; - -static BS::light_thread_pool* thread_pool; -static std::deque task_deque; - -static void task_process(Task* task) -{ - task->set_status(task_status::PROCESSING); - task->process(); - - if(task->get_status() == task_status::PROCESSING) { - // If the task status is still PROCESSING - // it can be deduced it hasn't been cancelled - task->set_status(task_status::COMPLETED); - } -} - -task_status Task::get_status(void) const -{ - return m_status; -} - -void Task::set_status(task_status status) -{ - m_status = status; -} - -void threading::init(void) -{ - auto argument = io::cmdline::get("threads", DEFAULT_POOL_SIZE_ARG); - auto num_concurrent_threads = std::thread::hardware_concurrency(); - unsigned int thread_pool_size; - - if(num_concurrent_threads && 0 == argument.compare("max")) { - // Use the maximum available number of concurrent - // hardware threads provided by the implementation - thread_pool_size = num_concurrent_threads; - } - else { - if(num_concurrent_threads) { - auto result = std::from_chars(argument.data(), argument.data() + argument.size(), thread_pool_size); - - if(result.ec == std::errc()) { - thread_pool_size = math::clamp(thread_pool_size, 1U, num_concurrent_threads); - } - else { - thread_pool_size = 4U; - } - } - else { - auto result = std::from_chars(argument.data(), argument.data() + argument.size(), thread_pool_size); - - if(result.ec == std::errc()) { - thread_pool_size = math::max(thread_pool_size, 1U); - } - else { - thread_pool_size = 4U; - } - } - } - - spdlog::info("threading: using {} threads for pooling tasks", thread_pool_size); - - thread_pool = new BS::light_thread_pool(thread_pool_size); - - task_deque.clear(); -} - -void threading::shutdown(void) -{ - for(auto task : task_deque) { - auto status = task->get_status(); - if((status != task_status::CANCELLED) || (status != task_status::COMPLETED)) { - task->set_status(task_status::CANCELLED); - } - } - - thread_pool->purge(); - thread_pool->wait(); - - for(auto task : task_deque) - delete task; - task_deque.clear(); - - delete thread_pool; -} - -void threading::update(void) -{ - auto task_iter = task_deque.cbegin(); - - while(task_iter != task_deque.cend()) { - auto task_ptr = *task_iter; - auto status = task_ptr->get_status(); - - if(status == task_status::CANCELLED) { - delete task_ptr; - task_iter = task_deque.erase(task_iter); - continue; - } - - if(status == task_status::COMPLETED) { - task_ptr->finalize(); - delete task_ptr; - task_iter = task_deque.erase(task_iter); - continue; - } - - task_iter = std::next(task_iter); - } -} - -void threading::detail::submit_new(Task* task) -{ - task->set_status(task_status::ENQUEUED); - - static_cast(thread_pool->submit_task(std::bind(&task_process, task))); - - task_deque.push_back(task); -} +#include "core/pch.hh" + +#include "core/threading.hh" + +#include "core/io/cmdline.hh" + +#include "core/math/constexpr.hh" + +constexpr static std::string_view DEFAULT_POOL_SIZE_ARG = "4"; + +static BS::light_thread_pool* thread_pool; +static std::deque task_deque; + +static void task_process(Task* task) +{ + task->set_status(task_status::PROCESSING); + task->process(); + + if(task->get_status() == task_status::PROCESSING) { + // If the task status is still PROCESSING + // it can be deduced it hasn't been cancelled + task->set_status(task_status::COMPLETED); + } +} + +task_status Task::get_status(void) const +{ + return m_status; +} + +void Task::set_status(task_status status) +{ + m_status = status; +} + +void threading::init(void) +{ + auto argument = io::cmdline::get("threads", DEFAULT_POOL_SIZE_ARG); + auto num_concurrent_threads = std::thread::hardware_concurrency(); + unsigned int thread_pool_size; + + if(num_concurrent_threads && 0 == argument.compare("max")) { + // Use the maximum available number of concurrent + // hardware threads provided by the implementation + thread_pool_size = num_concurrent_threads; + } + else { + if(num_concurrent_threads) { + auto result = std::from_chars(argument.data(), argument.data() + argument.size(), thread_pool_size); + + if(result.ec == std::errc()) { + thread_pool_size = math::clamp(thread_pool_size, 1U, num_concurrent_threads); + } + else { + thread_pool_size = 4U; + } + } + else { + auto result = std::from_chars(argument.data(), argument.data() + argument.size(), thread_pool_size); + + if(result.ec == std::errc()) { + thread_pool_size = math::max(thread_pool_size, 1U); + } + else { + thread_pool_size = 4U; + } + } + } + + spdlog::info("threading: using {} threads for pooling tasks", thread_pool_size); + + thread_pool = new BS::light_thread_pool(thread_pool_size); + + task_deque.clear(); +} + +void threading::shutdown(void) +{ + for(auto task : task_deque) { + auto status = task->get_status(); + if((status != task_status::CANCELLED) || (status != task_status::COMPLETED)) { + task->set_status(task_status::CANCELLED); + } + } + + thread_pool->purge(); + thread_pool->wait(); + + for(auto task : task_deque) + delete task; + task_deque.clear(); + + delete thread_pool; +} + +void threading::update(void) +{ + auto task_iter = task_deque.cbegin(); + + while(task_iter != task_deque.cend()) { + auto task_ptr = *task_iter; + auto status = task_ptr->get_status(); + + if(status == task_status::CANCELLED) { + delete task_ptr; + task_iter = task_deque.erase(task_iter); + continue; + } + + if(status == task_status::COMPLETED) { + task_ptr->finalize(); + delete task_ptr; + task_iter = task_deque.erase(task_iter); + continue; + } + + task_iter = std::next(task_iter); + } +} + +void threading::detail::submit_new(Task* task) +{ + task->set_status(task_status::ENQUEUED); + + static_cast(thread_pool->submit_task(std::bind(&task_process, task))); + + task_deque.push_back(task); +} diff --git a/core/threading.hh b/core/threading.hh index 14f17f8..2225907 100644 --- a/core/threading.hh +++ b/core/threading.hh @@ -1,46 +1,46 @@ -#pragma once - -enum class task_status : unsigned int { - ENQUEUED = 0x0000U, - PROCESSING = 0x0001U, - COMPLETED = 0x0002U, - CANCELLED = 0x0004U, -}; - -class Task { -public: - virtual ~Task(void) = default; - virtual void process(void) = 0; - virtual void finalize(void) = 0; - - task_status get_status(void) const; - void set_status(task_status status); - -protected: - std::atomic m_status; - std::future m_future; -}; - -namespace threading -{ -void init(void); -void shutdown(void); -void update(void); -} // namespace threading - -namespace threading::detail -{ -void submit_new(Task* task); -} // namespace threading::detail - -namespace threading -{ -template -void submit(AT&&... args); -} // namespace threading - -template -inline void threading::submit(AT&&... args) -{ - threading::detail::submit_new(new T(args...)); -} +#pragma once + +enum class task_status : unsigned int { + ENQUEUED = 0x0000U, + PROCESSING = 0x0001U, + COMPLETED = 0x0002U, + CANCELLED = 0x0004U, +}; + +class Task { +public: + virtual ~Task(void) = default; + virtual void process(void) = 0; + virtual void finalize(void) = 0; + + task_status get_status(void) const; + void set_status(task_status status); + +protected: + std::atomic m_status; + std::future m_future; +}; + +namespace threading +{ +void init(void); +void shutdown(void); +void update(void); +} // namespace threading + +namespace threading::detail +{ +void submit_new(Task* task); +} // namespace threading::detail + +namespace threading +{ +template +void submit(AT&&... args); +} // namespace threading + +template +inline void threading::submit(AT&&... args) +{ + threading::detail::submit_new(new T(args...)); +} diff --git a/core/utils/epoch.cc b/core/utils/epoch.cc index 36bdb79..be5d4bd 100644 --- a/core/utils/epoch.cc +++ b/core/utils/epoch.cc @@ -1,39 +1,39 @@ -#include "core/pch.hh" - -#include "core/utils/epoch.hh" - -std::uint64_t utils::unix_seconds(void) -{ - const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); - return static_cast(std::chrono::duration_cast(elapsed).count()); -} - -std::uint64_t utils::unix_milliseconds(void) -{ - const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); - return static_cast(std::chrono::duration_cast(elapsed).count()); -} - -std::uint64_t utils::unix_microseconds(void) -{ - const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); - return static_cast(std::chrono::duration_cast(elapsed).count()); -} - -std::int64_t utils::signed_unix_seconds(void) -{ - const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); - return static_cast(std::chrono::duration_cast(elapsed).count()); -} - -std::int64_t utils::signed_unix_milliseconds(void) -{ - const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); - return static_cast(std::chrono::duration_cast(elapsed).count()); -} - -std::int64_t utils::signed_unix_microseconds(void) -{ - const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); - return static_cast(std::chrono::duration_cast(elapsed).count()); -} +#include "core/pch.hh" + +#include "core/utils/epoch.hh" + +std::uint64_t utils::unix_seconds(void) +{ + const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(elapsed).count()); +} + +std::uint64_t utils::unix_milliseconds(void) +{ + const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(elapsed).count()); +} + +std::uint64_t utils::unix_microseconds(void) +{ + const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(elapsed).count()); +} + +std::int64_t utils::signed_unix_seconds(void) +{ + const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(elapsed).count()); +} + +std::int64_t utils::signed_unix_milliseconds(void) +{ + const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(elapsed).count()); +} + +std::int64_t utils::signed_unix_microseconds(void) +{ + const auto elapsed = std::chrono::system_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(elapsed).count()); +} diff --git a/core/utils/epoch.hh b/core/utils/epoch.hh index 4bf5460..1df564c 100644 --- a/core/utils/epoch.hh +++ b/core/utils/epoch.hh @@ -1,15 +1,15 @@ -#pragma once - -namespace utils -{ -std::uint64_t unix_seconds(void); -std::uint64_t unix_milliseconds(void); -std::uint64_t unix_microseconds(void); -} // namespace utils - -namespace utils -{ -std::int64_t signed_unix_seconds(void); -std::int64_t signed_unix_milliseconds(void); -std::int64_t signed_unix_microseconds(void); -} // namespace utils +#pragma once + +namespace utils +{ +std::uint64_t unix_seconds(void); +std::uint64_t unix_milliseconds(void); +std::uint64_t unix_microseconds(void); +} // namespace utils + +namespace utils +{ +std::int64_t signed_unix_seconds(void); +std::int64_t signed_unix_milliseconds(void); +std::int64_t signed_unix_microseconds(void); +} // namespace utils diff --git a/core/utils/physfs.cc b/core/utils/physfs.cc index cb310df..b801963 100644 --- a/core/utils/physfs.cc +++ b/core/utils/physfs.cc @@ -1,76 +1,76 @@ -#include "core/pch.hh" - -#include "core/utils/physfs.hh" - -bool utils::read_file(std::string_view path, std::vector& buffer) -{ - auto file = PHYSFS_openRead(std::string(path).c_str()); - - if(file == nullptr) { - spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); - return false; - } - - PHYSFS_sint64 file_size = PHYSFS_fileLength(file); - buffer.resize(static_cast(file_size)); - - PHYSFS_readBytes(file, buffer.data(), file_size); - PHYSFS_close(file); - - return true; -} - -bool utils::read_file(std::string_view path, std::string& buffer) -{ - auto file = PHYSFS_openRead(std::string(path).c_str()); - - if(file == nullptr) { - spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); - return false; - } - - PHYSFS_sint64 file_size = PHYSFS_fileLength(file); - buffer.resize(static_cast(file_size)); - - PHYSFS_readBytes(file, buffer.data(), file_size); - PHYSFS_close(file); - - return true; -} - -bool utils::write_file(std::string_view path, const std::vector& buffer) -{ - auto file = PHYSFS_openWrite(std::string(path).c_str()); - - if(file == nullptr) { - spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); - return false; - } - - PHYSFS_writeBytes(file, buffer.data(), static_cast(buffer.size())); - PHYSFS_close(file); - - return true; -} - -bool utils::write_file(std::string_view path, const std::string& buffer) -{ - auto file = PHYSFS_openWrite(std::string(path).c_str()); - - if(file == nullptr) { - spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); - return false; - } - - PHYSFS_writeBytes(file, buffer.data(), static_cast(buffer.size())); - PHYSFS_close(file); - - return true; -} - -std::string_view utils::physfs_error(void) -{ - auto error_code = PHYSFS_getLastErrorCode(); - auto error_string = PHYSFS_getErrorByCode(error_code); - return std::string_view(error_string, std::strlen(error_string)); -} +#include "core/pch.hh" + +#include "core/utils/physfs.hh" + +bool utils::read_file(std::string_view path, std::vector& buffer) +{ + auto file = PHYSFS_openRead(std::string(path).c_str()); + + if(file == nullptr) { + spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); + return false; + } + + PHYSFS_sint64 file_size = PHYSFS_fileLength(file); + buffer.resize(static_cast(file_size)); + + PHYSFS_readBytes(file, buffer.data(), file_size); + PHYSFS_close(file); + + return true; +} + +bool utils::read_file(std::string_view path, std::string& buffer) +{ + auto file = PHYSFS_openRead(std::string(path).c_str()); + + if(file == nullptr) { + spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); + return false; + } + + PHYSFS_sint64 file_size = PHYSFS_fileLength(file); + buffer.resize(static_cast(file_size)); + + PHYSFS_readBytes(file, buffer.data(), file_size); + PHYSFS_close(file); + + return true; +} + +bool utils::write_file(std::string_view path, const std::vector& buffer) +{ + auto file = PHYSFS_openWrite(std::string(path).c_str()); + + if(file == nullptr) { + spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); + return false; + } + + PHYSFS_writeBytes(file, buffer.data(), static_cast(buffer.size())); + PHYSFS_close(file); + + return true; +} + +bool utils::write_file(std::string_view path, const std::string& buffer) +{ + auto file = PHYSFS_openWrite(std::string(path).c_str()); + + if(file == nullptr) { + spdlog::error("physfs: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); + return false; + } + + PHYSFS_writeBytes(file, buffer.data(), static_cast(buffer.size())); + PHYSFS_close(file); + + return true; +} + +std::string_view utils::physfs_error(void) +{ + auto error_code = PHYSFS_getLastErrorCode(); + auto error_string = PHYSFS_getErrorByCode(error_code); + return std::string_view(error_string, std::strlen(error_string)); +} diff --git a/core/utils/physfs.hh b/core/utils/physfs.hh index 4af94dc..220954e 100644 --- a/core/utils/physfs.hh +++ b/core/utils/physfs.hh @@ -1,14 +1,14 @@ -#pragma once - -namespace utils -{ -bool read_file(std::string_view path, std::vector& buffer); -bool read_file(std::string_view path, std::string& buffer); -bool write_file(std::string_view path, const std::vector& buffer); -bool write_file(std::string_view path, const std::string& buffer); -} // namespace utils - -namespace utils -{ -std::string_view physfs_error(void); -} // namespace utils +#pragma once + +namespace utils +{ +bool read_file(std::string_view path, std::vector& buffer); +bool read_file(std::string_view path, std::string& buffer); +bool write_file(std::string_view path, const std::vector& buffer); +bool write_file(std::string_view path, const std::string& buffer); +} // namespace utils + +namespace utils +{ +std::string_view physfs_error(void); +} // namespace utils diff --git a/core/utils/string.cc b/core/utils/string.cc index dd3d567..4bdc073 100644 --- a/core/utils/string.cc +++ b/core/utils/string.cc @@ -1,57 +1,57 @@ -#include "core/pch.hh" - -#include "core/utils/string.hh" - -constexpr static const char* WHITESPACE_CHARS = " \t\r\n"; - -bool utils::is_whitespace(const std::string& string) -{ - if(string.find_first_not_of(WHITESPACE_CHARS) == std::string::npos) { - return true; - } - else if((string.size() == 1) && string[0] == 0x00) { - return true; - } - else { - return string.empty(); - } -} - -std::string utils::join(const std::vector& strings, const std::string& separator) -{ - std::ostringstream stream; - for(const std::string& str : strings) - stream << str << separator; - return stream.str(); -} - -std::vector utils::split(const std::string& string, const std::string& separator) -{ - std::size_t pos = 0; - std::size_t prev = 0; - std::vector result; - - while((pos = string.find(separator, prev)) != std::string::npos) { - result.push_back(string.substr(prev, pos - prev)); - prev = pos + separator.length(); - } - - if(prev <= string.length()) { - result.push_back(string.substr(prev, string.length() - prev)); - } - - return result; -} - -std::string utils::trim_whitespace(const std::string& string) -{ - auto su = string.find_first_not_of(WHITESPACE_CHARS); - auto sv = string.find_last_not_of(WHITESPACE_CHARS); - - if(su == std::string::npos) { - return std::string(); - } - else { - return string.substr(su, sv - su + 1); - } -} +#include "core/pch.hh" + +#include "core/utils/string.hh" + +constexpr static const char* WHITESPACE_CHARS = " \t\r\n"; + +bool utils::is_whitespace(const std::string& string) +{ + if(string.find_first_not_of(WHITESPACE_CHARS) == std::string::npos) { + return true; + } + else if((string.size() == 1) && string[0] == 0x00) { + return true; + } + else { + return string.empty(); + } +} + +std::string utils::join(const std::vector& strings, const std::string& separator) +{ + std::ostringstream stream; + for(const std::string& str : strings) + stream << str << separator; + return stream.str(); +} + +std::vector utils::split(const std::string& string, const std::string& separator) +{ + std::size_t pos = 0; + std::size_t prev = 0; + std::vector result; + + while((pos = string.find(separator, prev)) != std::string::npos) { + result.push_back(string.substr(prev, pos - prev)); + prev = pos + separator.length(); + } + + if(prev <= string.length()) { + result.push_back(string.substr(prev, string.length() - prev)); + } + + return result; +} + +std::string utils::trim_whitespace(const std::string& string) +{ + auto su = string.find_first_not_of(WHITESPACE_CHARS); + auto sv = string.find_last_not_of(WHITESPACE_CHARS); + + if(su == std::string::npos) { + return std::string(); + } + else { + return string.substr(su, sv - su + 1); + } +} diff --git a/core/utils/string.hh b/core/utils/string.hh index 827c3ca..0e896fd 100644 --- a/core/utils/string.hh +++ b/core/utils/string.hh @@ -1,17 +1,17 @@ -#pragma once - -namespace utils -{ -bool is_whitespace(const std::string& string); -} // namespace utils - -namespace utils -{ -std::string join(const std::vector& strings, const std::string& separator); -std::vector split(const std::string& string, const std::string& separator); -} // namespace utils - -namespace utils -{ -std::string trim_whitespace(const std::string& string); -} // namespace utils +#pragma once + +namespace utils +{ +bool is_whitespace(const std::string& string); +} // namespace utils + +namespace utils +{ +std::string join(const std::vector& strings, const std::string& separator); +std::vector split(const std::string& string, const std::string& separator); +} // namespace utils + +namespace utils +{ +std::string trim_whitespace(const std::string& string); +} // namespace utils diff --git a/core/version.hh b/core/version.hh index fc33374..50f128a 100644 --- a/core/version.hh +++ b/core/version.hh @@ -1,14 +1,14 @@ -#pragma once - -namespace version -{ -extern const unsigned long major; -extern const unsigned long minor; -extern const unsigned long patch; -} // namespace version - -namespace version -{ -extern const std::string_view commit; -extern const std::string_view semver; -} // namespace version +#pragma once + +namespace version +{ +extern const unsigned long major; +extern const unsigned long minor; +extern const unsigned long patch; +} // namespace version + +namespace version +{ +extern const std::string_view commit; +extern const std::string_view semver; +} // namespace version diff --git a/game/client/config/gamepad_axis.cc b/game/client/config/gamepad_axis.cc index 8ae74be..c782c19 100644 --- a/game/client/config/gamepad_axis.cc +++ b/game/client/config/gamepad_axis.cc @@ -1,115 +1,115 @@ -#include "client/pch.hh" - -#include "client/config/gamepad_axis.hh" - -#include "core/math/constexpr.hh" - -#include "client/io/gamepad.hh" - -constexpr static std::string_view UNKNOWN_AXIS_NAME = "UNKNOWN"; - -static const std::pair axis_names[] = { - { GLFW_GAMEPAD_AXIS_LEFT_X, "LEFT_X" }, - { GLFW_GAMEPAD_AXIS_LEFT_Y, "LEFT_Y" }, - { GLFW_GAMEPAD_AXIS_RIGHT_X, "RIGHT_X" }, - { GLFW_GAMEPAD_AXIS_RIGHT_Y, "RIGHT_Y" }, - { GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, "LEFT_TRIG" }, - { GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, "RIGHT_TRIG" }, -}; - -static std::string_view get_axis_name(int axis) -{ - for(const auto& it : axis_names) { - if(it.first != axis) { - continue; - } - - return it.second; - } - - return UNKNOWN_AXIS_NAME; -} - -config::GamepadAxis::GamepadAxis(void) : GamepadAxis(io::INVALID_GAMEPAD_AXIS, false) -{ -} - -config::GamepadAxis::GamepadAxis(int axis, bool inverted) -{ - m_inverted = inverted; - m_gamepad_axis = axis; - m_name = get_axis_name(axis); - m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); -} - -std::string_view config::GamepadAxis::get(void) const -{ - return m_full_string; -} - -void config::GamepadAxis::set(std::string_view value) -{ - char new_name[64]; - unsigned int new_invert; - std::string value_str(value); - - if(2 == std::sscanf(value_str.c_str(), "%63[^:]:%u", new_name, &new_invert)) { - for(const auto& it : axis_names) { - if(0 == it.second.compare(new_name)) { - m_inverted = new_invert; - m_gamepad_axis = it.first; - m_name = get_axis_name(m_gamepad_axis); - m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); - return; - } - } - } - - m_inverted = false; - m_gamepad_axis = io::INVALID_GAMEPAD_AXIS; - m_name = UNKNOWN_AXIS_NAME; - m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); -} - -int config::GamepadAxis::get_axis(void) const -{ - return m_gamepad_axis; -} - -void config::GamepadAxis::set_axis(int axis) -{ - m_gamepad_axis = axis; - m_name = get_axis_name(axis); - m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); -} - -bool config::GamepadAxis::is_inverted(void) const -{ - return m_inverted; -} - -void config::GamepadAxis::set_inverted(bool inverted) -{ - m_inverted = inverted; - m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); -} - -float config::GamepadAxis::get_value(const GLFWgamepadstate& state, float deadzone) const -{ - if(m_gamepad_axis <= math::array_size(state.axes)) { - auto value = state.axes[m_gamepad_axis]; - - if(math::abs(value) > deadzone) { - return m_inverted ? -value : value; - } - - return 0.0f; - } - - return 0.0f; -} - -std::string_view config::GamepadAxis::get_name(void) const -{ - return m_name; -} +#include "client/pch.hh" + +#include "client/config/gamepad_axis.hh" + +#include "core/math/constexpr.hh" + +#include "client/io/gamepad.hh" + +constexpr static std::string_view UNKNOWN_AXIS_NAME = "UNKNOWN"; + +static const std::pair axis_names[] = { + { GLFW_GAMEPAD_AXIS_LEFT_X, "LEFT_X" }, + { GLFW_GAMEPAD_AXIS_LEFT_Y, "LEFT_Y" }, + { GLFW_GAMEPAD_AXIS_RIGHT_X, "RIGHT_X" }, + { GLFW_GAMEPAD_AXIS_RIGHT_Y, "RIGHT_Y" }, + { GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, "LEFT_TRIG" }, + { GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, "RIGHT_TRIG" }, +}; + +static std::string_view get_axis_name(int axis) +{ + for(const auto& it : axis_names) { + if(it.first != axis) { + continue; + } + + return it.second; + } + + return UNKNOWN_AXIS_NAME; +} + +config::GamepadAxis::GamepadAxis(void) : GamepadAxis(io::INVALID_GAMEPAD_AXIS, false) +{ +} + +config::GamepadAxis::GamepadAxis(int axis, bool inverted) +{ + m_inverted = inverted; + m_gamepad_axis = axis; + m_name = get_axis_name(axis); + m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); +} + +std::string_view config::GamepadAxis::get(void) const +{ + return m_full_string; +} + +void config::GamepadAxis::set(std::string_view value) +{ + char new_name[64]; + unsigned int new_invert; + std::string value_str(value); + + if(2 == std::sscanf(value_str.c_str(), "%63[^:]:%u", new_name, &new_invert)) { + for(const auto& it : axis_names) { + if(0 == it.second.compare(new_name)) { + m_inverted = new_invert; + m_gamepad_axis = it.first; + m_name = get_axis_name(m_gamepad_axis); + m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); + return; + } + } + } + + m_inverted = false; + m_gamepad_axis = io::INVALID_GAMEPAD_AXIS; + m_name = UNKNOWN_AXIS_NAME; + m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); +} + +int config::GamepadAxis::get_axis(void) const +{ + return m_gamepad_axis; +} + +void config::GamepadAxis::set_axis(int axis) +{ + m_gamepad_axis = axis; + m_name = get_axis_name(axis); + m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); +} + +bool config::GamepadAxis::is_inverted(void) const +{ + return m_inverted; +} + +void config::GamepadAxis::set_inverted(bool inverted) +{ + m_inverted = inverted; + m_full_string = std::format("{}:{}", m_name, m_inverted ? 1U : 0U); +} + +float config::GamepadAxis::get_value(const GLFWgamepadstate& state, float deadzone) const +{ + if(m_gamepad_axis <= math::array_size(state.axes)) { + auto value = state.axes[m_gamepad_axis]; + + if(math::abs(value) > deadzone) { + return m_inverted ? -value : value; + } + + return 0.0f; + } + + return 0.0f; +} + +std::string_view config::GamepadAxis::get_name(void) const +{ + return m_name; +} diff --git a/game/client/config/gamepad_axis.hh b/game/client/config/gamepad_axis.hh index 9392a35..80c323f 100644 --- a/game/client/config/gamepad_axis.hh +++ b/game/client/config/gamepad_axis.hh @@ -1,38 +1,38 @@ -#pragma once - -#include "core/config/ivalue.hh" - -struct GLFWgamepadstate; - -namespace config -{ -class GamepadAxis final : public IValue { -public: - explicit GamepadAxis(void); - explicit GamepadAxis(int axis, bool inverted); - virtual ~GamepadAxis(void) = default; - - virtual std::string_view get(void) const override; - virtual void set(std::string_view value) override; - - int get_axis(void) const; - void set_axis(int axis); - - bool is_inverted(void) const; - void set_inverted(bool inverted); - - float get_value(const GLFWgamepadstate& state, float deadzone = 0.0f) const; - - // Conventional get/set methods implemented by - // this configuration value actually contain the - // inversion flag. Since we're updating that flag - // in the UI by means of a separate checkbox, we only need the name here - std::string_view get_name(void) const; - -private: - bool m_inverted; - int m_gamepad_axis; - std::string m_full_string; - std::string_view m_name; -}; -} // namespace config +#pragma once + +#include "core/config/ivalue.hh" + +struct GLFWgamepadstate; + +namespace config +{ +class GamepadAxis final : public IValue { +public: + explicit GamepadAxis(void); + explicit GamepadAxis(int axis, bool inverted); + virtual ~GamepadAxis(void) = default; + + virtual std::string_view get(void) const override; + virtual void set(std::string_view value) override; + + int get_axis(void) const; + void set_axis(int axis); + + bool is_inverted(void) const; + void set_inverted(bool inverted); + + float get_value(const GLFWgamepadstate& state, float deadzone = 0.0f) const; + + // Conventional get/set methods implemented by + // this configuration value actually contain the + // inversion flag. Since we're updating that flag + // in the UI by means of a separate checkbox, we only need the name here + std::string_view get_name(void) const; + +private: + bool m_inverted; + int m_gamepad_axis; + std::string m_full_string; + std::string_view m_name; +}; +} // namespace config diff --git a/game/client/config/gamepad_button.cc b/game/client/config/gamepad_button.cc index 07e4457..5141de3 100644 --- a/game/client/config/gamepad_button.cc +++ b/game/client/config/gamepad_button.cc @@ -1,90 +1,90 @@ -#include "client/pch.hh" - -#include "client/config/gamepad_button.hh" - -#include "core/math/constexpr.hh" - -#include "client/io/gamepad.hh" - -constexpr static std::string_view UNKNOWN_BUTTON_NAME = "UNKNOWN"; - -static const std::pair button_names[] = { - { GLFW_GAMEPAD_BUTTON_A, "A" }, - { GLFW_GAMEPAD_BUTTON_B, "B" }, - { GLFW_GAMEPAD_BUTTON_X, "X" }, - { GLFW_GAMEPAD_BUTTON_Y, "Y" }, - { GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, "L_BUMP" }, - { GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, "R_BUMP" }, - { GLFW_GAMEPAD_BUTTON_BACK, "BACK" }, - { GLFW_GAMEPAD_BUTTON_START, "START" }, - { GLFW_GAMEPAD_BUTTON_GUIDE, "GUIDE" }, - { GLFW_GAMEPAD_BUTTON_LEFT_THUMB, "L_THUMB" }, - { GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, "R_THUMB" }, - { GLFW_GAMEPAD_BUTTON_DPAD_UP, "DPAD_UP" }, - { GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, "DPAD_RIGHT" }, - { GLFW_GAMEPAD_BUTTON_DPAD_DOWN, "DPAD_DOWN" }, - { GLFW_GAMEPAD_BUTTON_DPAD_LEFT, "DPAD_LEFT" }, -}; - -static std::string_view get_button_name(int button) -{ - for(const auto& it : button_names) { - if(it.first == button) { - return it.second; - } - } - - return UNKNOWN_BUTTON_NAME; -} - -config::GamepadButton::GamepadButton(void) -{ - m_gamepad_button = io::INVALID_GAMEPAD_BUTTON; - m_name = UNKNOWN_BUTTON_NAME; -} - -config::GamepadButton::GamepadButton(int button) -{ - m_gamepad_button = button; - m_name = get_button_name(button); -} - -std::string_view config::GamepadButton::get(void) const -{ - return m_name; -} - -void config::GamepadButton::set(std::string_view value) -{ - for(const auto& it : button_names) { - if(0 == it.second.compare(value)) { - m_gamepad_button = it.first; - m_name = it.second; - return; - } - } - - m_gamepad_button = io::INVALID_GAMEPAD_BUTTON; - m_name = UNKNOWN_BUTTON_NAME; -} - -int config::GamepadButton::get_button(void) const -{ - return m_gamepad_button; -} - -void config::GamepadButton::set_button(int button) -{ - m_gamepad_button = button; - m_name = get_button_name(button); -} - -bool config::GamepadButton::equals(int button) const -{ - return m_gamepad_button == button; -} - -bool config::GamepadButton::is_pressed(const GLFWgamepadstate& state) const -{ - return m_gamepad_button < math::array_size(state.buttons) && state.buttons[m_gamepad_button] == GLFW_PRESS; -} +#include "client/pch.hh" + +#include "client/config/gamepad_button.hh" + +#include "core/math/constexpr.hh" + +#include "client/io/gamepad.hh" + +constexpr static std::string_view UNKNOWN_BUTTON_NAME = "UNKNOWN"; + +static const std::pair button_names[] = { + { GLFW_GAMEPAD_BUTTON_A, "A" }, + { GLFW_GAMEPAD_BUTTON_B, "B" }, + { GLFW_GAMEPAD_BUTTON_X, "X" }, + { GLFW_GAMEPAD_BUTTON_Y, "Y" }, + { GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, "L_BUMP" }, + { GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, "R_BUMP" }, + { GLFW_GAMEPAD_BUTTON_BACK, "BACK" }, + { GLFW_GAMEPAD_BUTTON_START, "START" }, + { GLFW_GAMEPAD_BUTTON_GUIDE, "GUIDE" }, + { GLFW_GAMEPAD_BUTTON_LEFT_THUMB, "L_THUMB" }, + { GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, "R_THUMB" }, + { GLFW_GAMEPAD_BUTTON_DPAD_UP, "DPAD_UP" }, + { GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, "DPAD_RIGHT" }, + { GLFW_GAMEPAD_BUTTON_DPAD_DOWN, "DPAD_DOWN" }, + { GLFW_GAMEPAD_BUTTON_DPAD_LEFT, "DPAD_LEFT" }, +}; + +static std::string_view get_button_name(int button) +{ + for(const auto& it : button_names) { + if(it.first == button) { + return it.second; + } + } + + return UNKNOWN_BUTTON_NAME; +} + +config::GamepadButton::GamepadButton(void) +{ + m_gamepad_button = io::INVALID_GAMEPAD_BUTTON; + m_name = UNKNOWN_BUTTON_NAME; +} + +config::GamepadButton::GamepadButton(int button) +{ + m_gamepad_button = button; + m_name = get_button_name(button); +} + +std::string_view config::GamepadButton::get(void) const +{ + return m_name; +} + +void config::GamepadButton::set(std::string_view value) +{ + for(const auto& it : button_names) { + if(0 == it.second.compare(value)) { + m_gamepad_button = it.first; + m_name = it.second; + return; + } + } + + m_gamepad_button = io::INVALID_GAMEPAD_BUTTON; + m_name = UNKNOWN_BUTTON_NAME; +} + +int config::GamepadButton::get_button(void) const +{ + return m_gamepad_button; +} + +void config::GamepadButton::set_button(int button) +{ + m_gamepad_button = button; + m_name = get_button_name(button); +} + +bool config::GamepadButton::equals(int button) const +{ + return m_gamepad_button == button; +} + +bool config::GamepadButton::is_pressed(const GLFWgamepadstate& state) const +{ + return m_gamepad_button < math::array_size(state.buttons) && state.buttons[m_gamepad_button] == GLFW_PRESS; +} diff --git a/game/client/config/gamepad_button.hh b/game/client/config/gamepad_button.hh index 584c353..f11fe4f 100644 --- a/game/client/config/gamepad_button.hh +++ b/game/client/config/gamepad_button.hh @@ -1,28 +1,28 @@ -#pragma once - -#include "core/config/ivalue.hh" - -struct GLFWgamepadstate; - -namespace config -{ -class GamepadButton final : public IValue { -public: - explicit GamepadButton(void); - explicit GamepadButton(int button); - virtual ~GamepadButton(void) = default; - - virtual std::string_view get(void) const override; - virtual void set(std::string_view value) override; - - int get_button(void) const; - void set_button(int button); - - bool equals(int button) const; - bool is_pressed(const GLFWgamepadstate& state) const; - -private: - int m_gamepad_button; - std::string_view m_name; -}; -} // namespace config +#pragma once + +#include "core/config/ivalue.hh" + +struct GLFWgamepadstate; + +namespace config +{ +class GamepadButton final : public IValue { +public: + explicit GamepadButton(void); + explicit GamepadButton(int button); + virtual ~GamepadButton(void) = default; + + virtual std::string_view get(void) const override; + virtual void set(std::string_view value) override; + + int get_button(void) const; + void set_button(int button); + + bool equals(int button) const; + bool is_pressed(const GLFWgamepadstate& state) const; + +private: + int m_gamepad_button; + std::string_view m_name; +}; +} // namespace config diff --git a/game/client/config/keybind.cc b/game/client/config/keybind.cc index e254f7b..befdca2 100644 --- a/game/client/config/keybind.cc +++ b/game/client/config/keybind.cc @@ -1,202 +1,202 @@ -#include "client/pch.hh" - -#include "client/config/keybind.hh" - -#include "core/math/constexpr.hh" - -#include "client/const.hh" - -constexpr static std::string_view UNKNOWN_KEY_NAME = "UNKNOWN"; - -static const std::pair key_names[] = { - { GLFW_KEY_SPACE, "SPACE" }, - { GLFW_KEY_APOSTROPHE, "'" }, - { GLFW_KEY_COMMA, "," }, - { GLFW_KEY_MINUS, "-" }, - { GLFW_KEY_PERIOD, "." }, - { GLFW_KEY_SLASH, "/" }, - { GLFW_KEY_0, "0" }, - { GLFW_KEY_1, "1" }, - { GLFW_KEY_2, "2" }, - { GLFW_KEY_3, "3" }, - { GLFW_KEY_4, "4" }, - { GLFW_KEY_5, "5" }, - { GLFW_KEY_6, "6" }, - { GLFW_KEY_7, "7" }, - { GLFW_KEY_8, "8" }, - { GLFW_KEY_9, "9" }, - { GLFW_KEY_SEMICOLON, ";" }, - { GLFW_KEY_EQUAL, "=" }, - { GLFW_KEY_A, "A" }, - { GLFW_KEY_B, "B" }, - { GLFW_KEY_C, "C" }, - { GLFW_KEY_D, "D" }, - { GLFW_KEY_E, "E" }, - { GLFW_KEY_F, "F" }, - { GLFW_KEY_G, "G" }, - { GLFW_KEY_H, "H" }, - { GLFW_KEY_I, "I" }, - { GLFW_KEY_J, "J" }, - { GLFW_KEY_K, "K" }, - { GLFW_KEY_L, "L" }, - { GLFW_KEY_M, "M" }, - { GLFW_KEY_N, "N" }, - { GLFW_KEY_O, "O" }, - { GLFW_KEY_P, "P" }, - { GLFW_KEY_Q, "Q" }, - { GLFW_KEY_R, "R" }, - { GLFW_KEY_S, "S" }, - { GLFW_KEY_T, "T" }, - { GLFW_KEY_U, "U" }, - { GLFW_KEY_V, "V" }, - { GLFW_KEY_W, "W" }, - { GLFW_KEY_X, "X" }, - { GLFW_KEY_Y, "Y" }, - { GLFW_KEY_Z, "Z" }, - { GLFW_KEY_LEFT_BRACKET, "[" }, - { GLFW_KEY_BACKSLASH, "\\" }, - { GLFW_KEY_RIGHT_BRACKET, "]" }, - { GLFW_KEY_GRAVE_ACCENT, "`" }, - { GLFW_KEY_WORLD_1, "WORLD_1" }, - { GLFW_KEY_WORLD_2, "WORLD_2" }, - { GLFW_KEY_ESCAPE, "ESCAPE" }, - { GLFW_KEY_ENTER, "ENTER" }, - { GLFW_KEY_TAB, "TAB" }, - { GLFW_KEY_BACKSPACE, "BACKSPACE" }, - { GLFW_KEY_INSERT, "INSERT" }, - { GLFW_KEY_DELETE, "DELETE" }, - { GLFW_KEY_RIGHT, "RIGHT" }, - { GLFW_KEY_LEFT, "LEFT" }, - { GLFW_KEY_DOWN, "DOWN" }, - { GLFW_KEY_UP, "UP" }, - { GLFW_KEY_PAGE_UP, "PAGE_UP" }, - { GLFW_KEY_PAGE_DOWN, "PAGE_DOWN" }, - { GLFW_KEY_HOME, "HOME" }, - { GLFW_KEY_END, "END" }, - { GLFW_KEY_CAPS_LOCK, "CAPS_LOCK" }, - { GLFW_KEY_SCROLL_LOCK, "SCROLL_LOCK" }, - { GLFW_KEY_NUM_LOCK, "NUM_LOCK" }, - { GLFW_KEY_PRINT_SCREEN, "PRINT_SCREEN" }, - { GLFW_KEY_PAUSE, "PAUSE" }, - { GLFW_KEY_F1, "F1" }, - { GLFW_KEY_F2, "F2" }, - { GLFW_KEY_F3, "F3" }, - { GLFW_KEY_F4, "F4" }, - { GLFW_KEY_F5, "F5" }, - { GLFW_KEY_F6, "F6" }, - { GLFW_KEY_F7, "F7" }, - { GLFW_KEY_F8, "F8" }, - { GLFW_KEY_F9, "F9" }, - { GLFW_KEY_F10, "F10" }, - { GLFW_KEY_F11, "F11" }, - { GLFW_KEY_F12, "F12" }, - { GLFW_KEY_F13, "F13" }, - { GLFW_KEY_F14, "F14" }, - { GLFW_KEY_F15, "F15" }, - { GLFW_KEY_F16, "F16" }, - { GLFW_KEY_F17, "F17" }, - { GLFW_KEY_F18, "F18" }, - { GLFW_KEY_F19, "F19" }, - { GLFW_KEY_F20, "F20" }, - { GLFW_KEY_F21, "F21" }, - { GLFW_KEY_F22, "F22" }, - { GLFW_KEY_F23, "F23" }, - { GLFW_KEY_F24, "F24" }, - { GLFW_KEY_F25, "F25" }, - { GLFW_KEY_KP_0, "KEYPAD_0" }, - { GLFW_KEY_KP_1, "KEYPAD_1" }, - { GLFW_KEY_KP_2, "KEYPAD_2" }, - { GLFW_KEY_KP_3, "KEYPAD_3" }, - { GLFW_KEY_KP_4, "KEYPAD_4" }, - { GLFW_KEY_KP_5, "KEYPAD_5" }, - { GLFW_KEY_KP_6, "KEYPAD_6" }, - { GLFW_KEY_KP_7, "KEYPAD_7" }, - { GLFW_KEY_KP_8, "KEYPAD_8" }, - { GLFW_KEY_KP_9, "KEYPAD_9" }, - { GLFW_KEY_KP_DECIMAL, "KEYPAD_POINT" }, - { GLFW_KEY_KP_DIVIDE, "KEYPAD_DIV" }, - { GLFW_KEY_KP_MULTIPLY, "KEYPAD_MUL" }, - { GLFW_KEY_KP_SUBTRACT, "KEYPAD_MINUS" }, - { GLFW_KEY_KP_ADD, "KEYPAD_PLUS" }, - { GLFW_KEY_KP_ENTER, "KEYPAD_ENTER" }, - { GLFW_KEY_KP_EQUAL, "KEYPAD_EQUAL" }, - { GLFW_KEY_LEFT_SHIFT, "LEFT_SHIFT" }, - { GLFW_KEY_LEFT_CONTROL, "LEFT_CTRL" }, - { GLFW_KEY_LEFT_ALT, "LEFT_ALT" }, - { GLFW_KEY_LEFT_SUPER, "LEFT_SUPER" }, - { GLFW_KEY_RIGHT_SHIFT, "RIGHT_SHIFT" }, - { GLFW_KEY_RIGHT_CONTROL, "RIGHT_CTRL" }, - { GLFW_KEY_RIGHT_ALT, "RIGHT_ALT" }, - { GLFW_KEY_RIGHT_SUPER, "RIGHT_SUPER" }, - { GLFW_KEY_MENU, "MENU" }, -}; - -static std::string_view get_key_name(int keycode) -{ - for(const auto& it : key_names) { - if(it.first == keycode) { - return it.second; - } - } - - return UNKNOWN_KEY_NAME; -} - -config::KeyBind::KeyBind(void) -{ - m_glfw_keycode = GLFW_KEY_UNKNOWN; - m_name = UNKNOWN_KEY_NAME; -} - -config::KeyBind::KeyBind(int default_value) -{ - if(default_value == DEBUG_KEY) { - m_glfw_keycode = GLFW_KEY_UNKNOWN; - m_name = UNKNOWN_KEY_NAME; - } - else { - m_glfw_keycode = default_value; - m_name = get_key_name(default_value); - } -} - -void config::KeyBind::set(std::string_view value) -{ - for(const auto& it : key_names) { - if((it.first != DEBUG_KEY) && 0 == it.second.compare(value)) { - m_glfw_keycode = it.first; - m_name = it.second; - return; - } - } - - m_glfw_keycode = GLFW_KEY_UNKNOWN; - m_name = UNKNOWN_KEY_NAME; -} - -std::string_view config::KeyBind::get(void) const -{ - return m_name; -} - -void config::KeyBind::set_key(int keycode) -{ - if(keycode == DEBUG_KEY) { - m_glfw_keycode = GLFW_KEY_UNKNOWN; - m_name = UNKNOWN_KEY_NAME; - } - else { - m_glfw_keycode = keycode; - m_name = get_key_name(keycode); - } -} - -int config::KeyBind::get_key(void) const -{ - return m_glfw_keycode; -} - -bool config::KeyBind::equals(int keycode) const -{ - return m_glfw_keycode == keycode; -} +#include "client/pch.hh" + +#include "client/config/keybind.hh" + +#include "core/math/constexpr.hh" + +#include "client/const.hh" + +constexpr static std::string_view UNKNOWN_KEY_NAME = "UNKNOWN"; + +static const std::pair key_names[] = { + { GLFW_KEY_SPACE, "SPACE" }, + { GLFW_KEY_APOSTROPHE, "'" }, + { GLFW_KEY_COMMA, "," }, + { GLFW_KEY_MINUS, "-" }, + { GLFW_KEY_PERIOD, "." }, + { GLFW_KEY_SLASH, "/" }, + { GLFW_KEY_0, "0" }, + { GLFW_KEY_1, "1" }, + { GLFW_KEY_2, "2" }, + { GLFW_KEY_3, "3" }, + { GLFW_KEY_4, "4" }, + { GLFW_KEY_5, "5" }, + { GLFW_KEY_6, "6" }, + { GLFW_KEY_7, "7" }, + { GLFW_KEY_8, "8" }, + { GLFW_KEY_9, "9" }, + { GLFW_KEY_SEMICOLON, ";" }, + { GLFW_KEY_EQUAL, "=" }, + { GLFW_KEY_A, "A" }, + { GLFW_KEY_B, "B" }, + { GLFW_KEY_C, "C" }, + { GLFW_KEY_D, "D" }, + { GLFW_KEY_E, "E" }, + { GLFW_KEY_F, "F" }, + { GLFW_KEY_G, "G" }, + { GLFW_KEY_H, "H" }, + { GLFW_KEY_I, "I" }, + { GLFW_KEY_J, "J" }, + { GLFW_KEY_K, "K" }, + { GLFW_KEY_L, "L" }, + { GLFW_KEY_M, "M" }, + { GLFW_KEY_N, "N" }, + { GLFW_KEY_O, "O" }, + { GLFW_KEY_P, "P" }, + { GLFW_KEY_Q, "Q" }, + { GLFW_KEY_R, "R" }, + { GLFW_KEY_S, "S" }, + { GLFW_KEY_T, "T" }, + { GLFW_KEY_U, "U" }, + { GLFW_KEY_V, "V" }, + { GLFW_KEY_W, "W" }, + { GLFW_KEY_X, "X" }, + { GLFW_KEY_Y, "Y" }, + { GLFW_KEY_Z, "Z" }, + { GLFW_KEY_LEFT_BRACKET, "[" }, + { GLFW_KEY_BACKSLASH, "\\" }, + { GLFW_KEY_RIGHT_BRACKET, "]" }, + { GLFW_KEY_GRAVE_ACCENT, "`" }, + { GLFW_KEY_WORLD_1, "WORLD_1" }, + { GLFW_KEY_WORLD_2, "WORLD_2" }, + { GLFW_KEY_ESCAPE, "ESCAPE" }, + { GLFW_KEY_ENTER, "ENTER" }, + { GLFW_KEY_TAB, "TAB" }, + { GLFW_KEY_BACKSPACE, "BACKSPACE" }, + { GLFW_KEY_INSERT, "INSERT" }, + { GLFW_KEY_DELETE, "DELETE" }, + { GLFW_KEY_RIGHT, "RIGHT" }, + { GLFW_KEY_LEFT, "LEFT" }, + { GLFW_KEY_DOWN, "DOWN" }, + { GLFW_KEY_UP, "UP" }, + { GLFW_KEY_PAGE_UP, "PAGE_UP" }, + { GLFW_KEY_PAGE_DOWN, "PAGE_DOWN" }, + { GLFW_KEY_HOME, "HOME" }, + { GLFW_KEY_END, "END" }, + { GLFW_KEY_CAPS_LOCK, "CAPS_LOCK" }, + { GLFW_KEY_SCROLL_LOCK, "SCROLL_LOCK" }, + { GLFW_KEY_NUM_LOCK, "NUM_LOCK" }, + { GLFW_KEY_PRINT_SCREEN, "PRINT_SCREEN" }, + { GLFW_KEY_PAUSE, "PAUSE" }, + { GLFW_KEY_F1, "F1" }, + { GLFW_KEY_F2, "F2" }, + { GLFW_KEY_F3, "F3" }, + { GLFW_KEY_F4, "F4" }, + { GLFW_KEY_F5, "F5" }, + { GLFW_KEY_F6, "F6" }, + { GLFW_KEY_F7, "F7" }, + { GLFW_KEY_F8, "F8" }, + { GLFW_KEY_F9, "F9" }, + { GLFW_KEY_F10, "F10" }, + { GLFW_KEY_F11, "F11" }, + { GLFW_KEY_F12, "F12" }, + { GLFW_KEY_F13, "F13" }, + { GLFW_KEY_F14, "F14" }, + { GLFW_KEY_F15, "F15" }, + { GLFW_KEY_F16, "F16" }, + { GLFW_KEY_F17, "F17" }, + { GLFW_KEY_F18, "F18" }, + { GLFW_KEY_F19, "F19" }, + { GLFW_KEY_F20, "F20" }, + { GLFW_KEY_F21, "F21" }, + { GLFW_KEY_F22, "F22" }, + { GLFW_KEY_F23, "F23" }, + { GLFW_KEY_F24, "F24" }, + { GLFW_KEY_F25, "F25" }, + { GLFW_KEY_KP_0, "KEYPAD_0" }, + { GLFW_KEY_KP_1, "KEYPAD_1" }, + { GLFW_KEY_KP_2, "KEYPAD_2" }, + { GLFW_KEY_KP_3, "KEYPAD_3" }, + { GLFW_KEY_KP_4, "KEYPAD_4" }, + { GLFW_KEY_KP_5, "KEYPAD_5" }, + { GLFW_KEY_KP_6, "KEYPAD_6" }, + { GLFW_KEY_KP_7, "KEYPAD_7" }, + { GLFW_KEY_KP_8, "KEYPAD_8" }, + { GLFW_KEY_KP_9, "KEYPAD_9" }, + { GLFW_KEY_KP_DECIMAL, "KEYPAD_POINT" }, + { GLFW_KEY_KP_DIVIDE, "KEYPAD_DIV" }, + { GLFW_KEY_KP_MULTIPLY, "KEYPAD_MUL" }, + { GLFW_KEY_KP_SUBTRACT, "KEYPAD_MINUS" }, + { GLFW_KEY_KP_ADD, "KEYPAD_PLUS" }, + { GLFW_KEY_KP_ENTER, "KEYPAD_ENTER" }, + { GLFW_KEY_KP_EQUAL, "KEYPAD_EQUAL" }, + { GLFW_KEY_LEFT_SHIFT, "LEFT_SHIFT" }, + { GLFW_KEY_LEFT_CONTROL, "LEFT_CTRL" }, + { GLFW_KEY_LEFT_ALT, "LEFT_ALT" }, + { GLFW_KEY_LEFT_SUPER, "LEFT_SUPER" }, + { GLFW_KEY_RIGHT_SHIFT, "RIGHT_SHIFT" }, + { GLFW_KEY_RIGHT_CONTROL, "RIGHT_CTRL" }, + { GLFW_KEY_RIGHT_ALT, "RIGHT_ALT" }, + { GLFW_KEY_RIGHT_SUPER, "RIGHT_SUPER" }, + { GLFW_KEY_MENU, "MENU" }, +}; + +static std::string_view get_key_name(int keycode) +{ + for(const auto& it : key_names) { + if(it.first == keycode) { + return it.second; + } + } + + return UNKNOWN_KEY_NAME; +} + +config::KeyBind::KeyBind(void) +{ + m_glfw_keycode = GLFW_KEY_UNKNOWN; + m_name = UNKNOWN_KEY_NAME; +} + +config::KeyBind::KeyBind(int default_value) +{ + if(default_value == DEBUG_KEY) { + m_glfw_keycode = GLFW_KEY_UNKNOWN; + m_name = UNKNOWN_KEY_NAME; + } + else { + m_glfw_keycode = default_value; + m_name = get_key_name(default_value); + } +} + +void config::KeyBind::set(std::string_view value) +{ + for(const auto& it : key_names) { + if((it.first != DEBUG_KEY) && 0 == it.second.compare(value)) { + m_glfw_keycode = it.first; + m_name = it.second; + return; + } + } + + m_glfw_keycode = GLFW_KEY_UNKNOWN; + m_name = UNKNOWN_KEY_NAME; +} + +std::string_view config::KeyBind::get(void) const +{ + return m_name; +} + +void config::KeyBind::set_key(int keycode) +{ + if(keycode == DEBUG_KEY) { + m_glfw_keycode = GLFW_KEY_UNKNOWN; + m_name = UNKNOWN_KEY_NAME; + } + else { + m_glfw_keycode = keycode; + m_name = get_key_name(keycode); + } +} + +int config::KeyBind::get_key(void) const +{ + return m_glfw_keycode; +} + +bool config::KeyBind::equals(int keycode) const +{ + return m_glfw_keycode == keycode; +} diff --git a/game/client/config/keybind.hh b/game/client/config/keybind.hh index dff6c18..51a67d6 100644 --- a/game/client/config/keybind.hh +++ b/game/client/config/keybind.hh @@ -1,25 +1,25 @@ -#pragma once - -#include "core/config/ivalue.hh" - -namespace config -{ -class KeyBind final : public IValue { -public: - explicit KeyBind(void); - explicit KeyBind(int default_value); - virtual ~KeyBind(void) = default; - - virtual void set(std::string_view value) override; - virtual std::string_view get(void) const override; - - void set_key(int keycode); - int get_key(void) const; - - bool equals(int keycode) const; - -private: - std::string_view m_name; - int m_glfw_keycode; -}; -} // namespace config +#pragma once + +#include "core/config/ivalue.hh" + +namespace config +{ +class KeyBind final : public IValue { +public: + explicit KeyBind(void); + explicit KeyBind(int default_value); + virtual ~KeyBind(void) = default; + + virtual void set(std::string_view value) override; + virtual std::string_view get(void) const override; + + void set_key(int keycode); + int get_key(void) const; + + bool equals(int keycode) const; + +private: + std::string_view m_name; + int m_glfw_keycode; +}; +} // namespace config diff --git a/game/client/const.hh b/game/client/const.hh index 461b500..b1e458f 100644 --- a/game/client/const.hh +++ b/game/client/const.hh @@ -1,23 +1,23 @@ -#pragma once - -#include "shared/const.hh" - -// This key is then going to be reserved for only -// the debug toggles and users won't be able to -// use this key for conventional gameplay things -constexpr static int DEBUG_KEY = GLFW_KEY_F3; - -constexpr static int BASE_WIDTH = 320; -constexpr static int BASE_HEIGHT = 240; - -constexpr static int MIN_WIDTH = 2 * BASE_WIDTH; -constexpr static int MIN_HEIGHT = 2 * BASE_HEIGHT; - -constexpr static int DEFAULT_WIDTH = 720; -constexpr static int DEFAULT_HEIGHT = 480; - -static_assert(DEFAULT_WIDTH >= MIN_WIDTH); -static_assert(DEFAULT_HEIGHT >= MIN_HEIGHT); - -constexpr static float MIN_PITCH = 0.0625f; -constexpr static float MAX_PITCH = 10.0f; +#pragma once + +#include "shared/const.hh" + +// This key is then going to be reserved for only +// the debug toggles and users won't be able to +// use this key for conventional gameplay things +constexpr static int DEBUG_KEY = GLFW_KEY_F3; + +constexpr static int BASE_WIDTH = 320; +constexpr static int BASE_HEIGHT = 240; + +constexpr static int MIN_WIDTH = 2 * BASE_WIDTH; +constexpr static int MIN_HEIGHT = 2 * BASE_HEIGHT; + +constexpr static int DEFAULT_WIDTH = 720; +constexpr static int DEFAULT_HEIGHT = 480; + +static_assert(DEFAULT_WIDTH >= MIN_WIDTH); +static_assert(DEFAULT_HEIGHT >= MIN_HEIGHT); + +constexpr static float MIN_PITCH = 0.0625f; +constexpr static float MAX_PITCH = 10.0f; diff --git a/game/client/entity/camera.cc b/game/client/entity/camera.cc index c17291f..471f2b6 100644 --- a/game/client/entity/camera.cc +++ b/game/client/entity/camera.cc @@ -1,114 +1,114 @@ -#include "client/pch.hh" - -#include "client/entity/camera.hh" - -#include "core/config/number.hh" - -#include "core/io/config_map.hh" - -#include "core/math/angles.hh" - -#include "shared/entity/head.hh" -#include "shared/entity/transform.hh" -#include "shared/entity/velocity.hh" - -#include "shared/world/dimension.hh" - -#include "client/entity/player_move.hh" - -#include "client/gui/settings.hh" - -#include "client/const.hh" -#include "client/globals.hh" -#include "client/session.hh" -#include "client/toggles.hh" - -config::Float entity::camera::roll_angle(2.0f, 0.0f, 4.0f); -config::Float entity::camera::vertical_fov(90.0f, 45.0f, 110.0f); -config::Unsigned entity::camera::view_distance(16U, 4U, 32U); - -glm::fvec3 entity::camera::angles; -glm::fvec3 entity::camera::direction; -glm::fmat4x4 entity::camera::matrix; -chunk_pos entity::camera::position_chunk; -glm::fvec3 entity::camera::position_local; - -static void reset_camera(void) -{ - entity::camera::angles = glm::fvec3(0.0f, 0.0f, 0.0f); - entity::camera::direction = DIR_FORWARD; - entity::camera::matrix = glm::identity(); - entity::camera::position_chunk = chunk_pos(0, 0, 0); - entity::camera::position_local = glm::fvec3(0.0f, 0.0f, 0.0f); -} - -// Gracefully contributed by PQCraft himself in 2024 -// making PlatinumSrc and Voxelius kind of related to each other -static glm::fmat4x4 platinumsrc_viewmatrix(const glm::fvec3& position, const glm::fvec3& angles) -{ - glm::fvec3 forward, up; - math::vectors(angles, &forward, nullptr, &up); - - auto result = glm::identity(); - result[0][0] = forward.y * up.z - forward.z * up.y; - result[1][0] = forward.z * up.x - forward.x * up.z; - result[2][0] = forward.x * up.y - forward.y * up.x; - result[3][0] = -result[0][0] * position.x - result[1][0] * position.y - result[2][0] * position.z; - result[0][1] = up.x; - result[1][1] = up.y; - result[2][1] = up.z; - result[3][1] = -up.x * position.x - up.y * position.y - up.z * position.z; - result[0][2] = -forward.x; - result[1][2] = -forward.y; - result[2][2] = -forward.z; - result[3][2] = forward.x * position.x + forward.y * position.y + forward.z * position.z; - return result; -} - -void entity::camera::init(void) -{ - globals::client_config.add_value("camera.roll_angle", entity::camera::roll_angle); - globals::client_config.add_value("camera.vertical_fov", entity::camera::vertical_fov); - globals::client_config.add_value("camera.view_distance", entity::camera::view_distance); - - settings::add_slider(1, entity::camera::vertical_fov, settings_location::GENERAL, "camera.vertical_fov", true, "%.0f"); - settings::add_slider(0, entity::camera::view_distance, settings_location::VIDEO, "camera.view_distance", false); - settings::add_slider(10, entity::camera::roll_angle, settings_location::VIDEO, "camera.roll_angle", true, "%.01f"); - - reset_camera(); -} - -void entity::camera::update(void) -{ - if(!session::is_ingame()) { - reset_camera(); - return; - } - - const auto& head = globals::dimension->entities.get(globals::player); - const auto& transform = globals::dimension->entities.get(globals::player); - const auto& velocity = globals::dimension->entities.get(globals::player); - - entity::camera::angles = transform.angles + head.angles; - entity::camera::position_chunk = transform.chunk; - entity::camera::position_local = transform.local + head.offset; - - glm::fvec3 right_vector, up_vector; - math::vectors(entity::camera::angles, &entity::camera::direction, &right_vector, &up_vector); - - auto client_angles = entity::camera::angles; - - if(!toggles::get(TOGGLE_PM_FLIGHT)) { - // Apply the quake-like view rolling - client_angles[2] = math::radians( - -entity::camera::roll_angle.get_value() * glm::dot(velocity.value / PMOVE_MAX_SPEED_GROUND, right_vector)); - } - - const auto z_near = 0.01f; - const auto z_far = 1.25f * static_cast(CHUNK_SIZE * entity::camera::view_distance.get_value()); - - auto proj = glm::perspective(math::radians(entity::camera::vertical_fov.get_value()), globals::aspect, z_near, z_far); - auto view = platinumsrc_viewmatrix(entity::camera::position_local, client_angles); - - entity::camera::matrix = proj * view; -} +#include "client/pch.hh" + +#include "client/entity/camera.hh" + +#include "core/config/number.hh" + +#include "core/io/config_map.hh" + +#include "core/math/angles.hh" + +#include "shared/entity/head.hh" +#include "shared/entity/transform.hh" +#include "shared/entity/velocity.hh" + +#include "shared/world/dimension.hh" + +#include "client/entity/player_move.hh" + +#include "client/gui/settings.hh" + +#include "client/const.hh" +#include "client/globals.hh" +#include "client/session.hh" +#include "client/toggles.hh" + +config::Float entity::camera::roll_angle(2.0f, 0.0f, 4.0f); +config::Float entity::camera::vertical_fov(90.0f, 45.0f, 110.0f); +config::Unsigned entity::camera::view_distance(16U, 4U, 32U); + +glm::fvec3 entity::camera::angles; +glm::fvec3 entity::camera::direction; +glm::fmat4x4 entity::camera::matrix; +chunk_pos entity::camera::position_chunk; +glm::fvec3 entity::camera::position_local; + +static void reset_camera(void) +{ + entity::camera::angles = glm::fvec3(0.0f, 0.0f, 0.0f); + entity::camera::direction = DIR_FORWARD; + entity::camera::matrix = glm::identity(); + entity::camera::position_chunk = chunk_pos(0, 0, 0); + entity::camera::position_local = glm::fvec3(0.0f, 0.0f, 0.0f); +} + +// Gracefully contributed by PQCraft himself in 2024 +// making PlatinumSrc and Voxelius kind of related to each other +static glm::fmat4x4 platinumsrc_viewmatrix(const glm::fvec3& position, const glm::fvec3& angles) +{ + glm::fvec3 forward, up; + math::vectors(angles, &forward, nullptr, &up); + + auto result = glm::identity(); + result[0][0] = forward.y * up.z - forward.z * up.y; + result[1][0] = forward.z * up.x - forward.x * up.z; + result[2][0] = forward.x * up.y - forward.y * up.x; + result[3][0] = -result[0][0] * position.x - result[1][0] * position.y - result[2][0] * position.z; + result[0][1] = up.x; + result[1][1] = up.y; + result[2][1] = up.z; + result[3][1] = -up.x * position.x - up.y * position.y - up.z * position.z; + result[0][2] = -forward.x; + result[1][2] = -forward.y; + result[2][2] = -forward.z; + result[3][2] = forward.x * position.x + forward.y * position.y + forward.z * position.z; + return result; +} + +void entity::camera::init(void) +{ + globals::client_config.add_value("camera.roll_angle", entity::camera::roll_angle); + globals::client_config.add_value("camera.vertical_fov", entity::camera::vertical_fov); + globals::client_config.add_value("camera.view_distance", entity::camera::view_distance); + + settings::add_slider(1, entity::camera::vertical_fov, settings_location::GENERAL, "camera.vertical_fov", true, "%.0f"); + settings::add_slider(0, entity::camera::view_distance, settings_location::VIDEO, "camera.view_distance", false); + settings::add_slider(10, entity::camera::roll_angle, settings_location::VIDEO, "camera.roll_angle", true, "%.01f"); + + reset_camera(); +} + +void entity::camera::update(void) +{ + if(!session::is_ingame()) { + reset_camera(); + return; + } + + const auto& head = globals::dimension->entities.get(globals::player); + const auto& transform = globals::dimension->entities.get(globals::player); + const auto& velocity = globals::dimension->entities.get(globals::player); + + entity::camera::angles = transform.angles + head.angles; + entity::camera::position_chunk = transform.chunk; + entity::camera::position_local = transform.local + head.offset; + + glm::fvec3 right_vector, up_vector; + math::vectors(entity::camera::angles, &entity::camera::direction, &right_vector, &up_vector); + + auto client_angles = entity::camera::angles; + + if(!toggles::get(TOGGLE_PM_FLIGHT)) { + // Apply the quake-like view rolling + client_angles[2] = math::radians(-entity::camera::roll_angle.get_value() + * glm::dot(velocity.value / PMOVE_MAX_SPEED_GROUND, right_vector)); + } + + const auto z_near = 0.01f; + const auto z_far = 1.25f * static_cast(CHUNK_SIZE * entity::camera::view_distance.get_value()); + + auto proj = glm::perspective(math::radians(entity::camera::vertical_fov.get_value()), globals::aspect, z_near, z_far); + auto view = platinumsrc_viewmatrix(entity::camera::position_local, client_angles); + + entity::camera::matrix = proj * view; +} diff --git a/game/client/entity/camera.hh b/game/client/entity/camera.hh index 67baf72..faefe78 100644 --- a/game/client/entity/camera.hh +++ b/game/client/entity/camera.hh @@ -1,31 +1,31 @@ -#pragma once - -#include "shared/types.hh" - -namespace config -{ -class Float; -class Unsigned; -} // namespace config - -namespace entity::camera -{ -extern config::Float roll_angle; -extern config::Float vertical_fov; -extern config::Unsigned view_distance; -} // namespace entity::camera - -namespace entity::camera -{ -extern glm::fvec3 angles; -extern glm::fvec3 direction; -extern glm::fmat4x4 matrix; -extern chunk_pos position_chunk; -extern glm::fvec3 position_local; -} // namespace entity::camera - -namespace entity::camera -{ -void init(void); -void update(void); -} // namespace entity::camera +#pragma once + +#include "shared/types.hh" + +namespace config +{ +class Float; +class Unsigned; +} // namespace config + +namespace entity::camera +{ +extern config::Float roll_angle; +extern config::Float vertical_fov; +extern config::Unsigned view_distance; +} // namespace entity::camera + +namespace entity::camera +{ +extern glm::fvec3 angles; +extern glm::fvec3 direction; +extern glm::fmat4x4 matrix; +extern chunk_pos position_chunk; +extern glm::fvec3 position_local; +} // namespace entity::camera + +namespace entity::camera +{ +void init(void); +void update(void); +} // namespace entity::camera diff --git a/game/client/entity/factory.cc b/game/client/entity/factory.cc index f6f6079..5a1785a 100644 --- a/game/client/entity/factory.cc +++ b/game/client/entity/factory.cc @@ -1,30 +1,30 @@ -#include "client/pch.hh" - -#include "client/entity/factory.hh" - -#include "shared/entity/factory.hh" -#include "shared/entity/head.hh" -#include "shared/entity/transform.hh" - -#include "shared/world/dimension.hh" - -#include "client/entity/sound_emitter.hh" - -#include "client/globals.hh" - -void entity::client::create_player(world::Dimension* dimension, entt::entity entity) -{ - entity::shared::create_player(dimension, entity); - - const auto& head = dimension->entities.get(entity); - dimension->entities.emplace_or_replace(entity, head); - dimension->entities.emplace_or_replace(entity, head); - - const auto& transform = dimension->entities.get(entity); - dimension->entities.emplace_or_replace(entity, transform); - dimension->entities.emplace_or_replace(entity, transform); - - if(globals::sound_ctx) { - dimension->entities.emplace_or_replace(entity); - } -} +#include "client/pch.hh" + +#include "client/entity/factory.hh" + +#include "shared/entity/factory.hh" +#include "shared/entity/head.hh" +#include "shared/entity/transform.hh" + +#include "shared/world/dimension.hh" + +#include "client/entity/sound_emitter.hh" + +#include "client/globals.hh" + +void entity::client::create_player(world::Dimension* dimension, entt::entity entity) +{ + entity::shared::create_player(dimension, entity); + + const auto& head = dimension->entities.get(entity); + dimension->entities.emplace_or_replace(entity, head); + dimension->entities.emplace_or_replace(entity, head); + + const auto& transform = dimension->entities.get(entity); + dimension->entities.emplace_or_replace(entity, transform); + dimension->entities.emplace_or_replace(entity, transform); + + if(globals::sound_ctx) { + dimension->entities.emplace_or_replace(entity); + } +} diff --git a/game/client/entity/factory.hh b/game/client/entity/factory.hh index 63e6e44..8cc8208 100644 --- a/game/client/entity/factory.hh +++ b/game/client/entity/factory.hh @@ -1,11 +1,11 @@ -#pragma once - -namespace world -{ -class Dimension; -} // namespace world - -namespace entity::client -{ -void create_player(world::Dimension* dimension, entt::entity entity); -} // namespace entity::client +#pragma once + +namespace world +{ +class Dimension; +} // namespace world + +namespace entity::client +{ +void create_player(world::Dimension* dimension, entt::entity entity); +} // namespace entity::client diff --git a/game/client/entity/interpolation.cc b/game/client/entity/interpolation.cc index 9eca735..ef23a4c 100644 --- a/game/client/entity/interpolation.cc +++ b/game/client/entity/interpolation.cc @@ -1,64 +1,64 @@ -#include "client/pch.hh" - -#include "client/entity/interpolation.hh" - -#include "core/math/constexpr.hh" - -#include "shared/entity/head.hh" -#include "shared/entity/transform.hh" - -#include "shared/world/dimension.hh" - -#include "shared/coord.hh" - -#include "client/globals.hh" - -static void transform_interpolate(float alpha) -{ - auto group = globals::dimension->entities.group( - entt::get); - - for(auto [entity, interp, current, previous] : group.each()) { - interp.angles[0] = math::lerp(previous.angles[0], current.angles[0], alpha); - interp.angles[1] = math::lerp(previous.angles[1], current.angles[1], alpha); - interp.angles[2] = math::lerp(previous.angles[2], current.angles[2], alpha); - - // Figure out previous chunk-local floating-point coordinates transformed - // to the current WorldCoord's chunk domain coordinates; we're interpolating - // against these instead of using previous.position.local to prevent jittering - auto previous_shift = coord::to_relative(current.chunk, current.local, previous.chunk, previous.local); - auto previous_local = current.local + previous_shift; - - interp.chunk.x = current.chunk.x; - interp.chunk.y = current.chunk.y; - interp.chunk.z = current.chunk.z; - - interp.local.x = math::lerp(previous_local.x, current.local.x, alpha); - interp.local.y = math::lerp(previous_local.y, current.local.y, alpha); - interp.local.z = math::lerp(previous_local.z, current.local.z, alpha); - } -} - -static void head_interpolate(float alpha) -{ - auto group = globals::dimension->entities.group(entt::get); - - for(auto [entity, interp, current, previous] : group.each()) { - interp.angles[0] = math::lerp(previous.angles[0], current.angles[0], alpha); - interp.angles[1] = math::lerp(previous.angles[1], current.angles[1], alpha); - interp.angles[2] = math::lerp(previous.angles[2], current.angles[2], alpha); - - interp.offset.x = math::lerp(previous.offset.x, current.offset.x, alpha); - interp.offset.y = math::lerp(previous.offset.y, current.offset.y, alpha); - interp.offset.z = math::lerp(previous.offset.z, current.offset.z, alpha); - } -} - -void entity::interpolation::update(void) -{ - if(globals::dimension) { - auto alpha = static_cast(globals::fixed_accumulator) / static_cast(globals::fixed_frametime_us); - transform_interpolate(alpha); - head_interpolate(alpha); - } +#include "client/pch.hh" + +#include "client/entity/interpolation.hh" + +#include "core/math/constexpr.hh" + +#include "shared/entity/head.hh" +#include "shared/entity/transform.hh" + +#include "shared/world/dimension.hh" + +#include "shared/coord.hh" + +#include "client/globals.hh" + +static void transform_interpolate(float alpha) +{ + auto group = globals::dimension->entities.group( + entt::get); + + for(auto [entity, interp, current, previous] : group.each()) { + interp.angles[0] = math::lerp(previous.angles[0], current.angles[0], alpha); + interp.angles[1] = math::lerp(previous.angles[1], current.angles[1], alpha); + interp.angles[2] = math::lerp(previous.angles[2], current.angles[2], alpha); + + // Figure out previous chunk-local floating-point coordinates transformed + // to the current WorldCoord's chunk domain coordinates; we're interpolating + // against these instead of using previous.position.local to prevent jittering + auto previous_shift = coord::to_relative(current.chunk, current.local, previous.chunk, previous.local); + auto previous_local = current.local + previous_shift; + + interp.chunk.x = current.chunk.x; + interp.chunk.y = current.chunk.y; + interp.chunk.z = current.chunk.z; + + interp.local.x = math::lerp(previous_local.x, current.local.x, alpha); + interp.local.y = math::lerp(previous_local.y, current.local.y, alpha); + interp.local.z = math::lerp(previous_local.z, current.local.z, alpha); + } +} + +static void head_interpolate(float alpha) +{ + auto group = globals::dimension->entities.group(entt::get); + + for(auto [entity, interp, current, previous] : group.each()) { + interp.angles[0] = math::lerp(previous.angles[0], current.angles[0], alpha); + interp.angles[1] = math::lerp(previous.angles[1], current.angles[1], alpha); + interp.angles[2] = math::lerp(previous.angles[2], current.angles[2], alpha); + + interp.offset.x = math::lerp(previous.offset.x, current.offset.x, alpha); + interp.offset.y = math::lerp(previous.offset.y, current.offset.y, alpha); + interp.offset.z = math::lerp(previous.offset.z, current.offset.z, alpha); + } +} + +void entity::interpolation::update(void) +{ + if(globals::dimension) { + auto alpha = static_cast(globals::fixed_accumulator) / static_cast(globals::fixed_frametime_us); + transform_interpolate(alpha); + head_interpolate(alpha); + } } \ No newline at end of file diff --git a/game/client/entity/interpolation.hh b/game/client/entity/interpolation.hh index 6935fe8..a7c4dac 100644 --- a/game/client/entity/interpolation.hh +++ b/game/client/entity/interpolation.hh @@ -1,6 +1,6 @@ -#pragma once - -namespace entity::interpolation -{ -void update(void); -} // namespace entity::interpolation +#pragma once + +namespace entity::interpolation +{ +void update(void); +} // namespace entity::interpolation diff --git a/game/client/entity/listener.cc b/game/client/entity/listener.cc index 3b1a35b..3d732ae 100644 --- a/game/client/entity/listener.cc +++ b/game/client/entity/listener.cc @@ -1,42 +1,42 @@ -#include "client/pch.hh" - -#include "client/entity/listener.hh" - -#include "core/config/number.hh" - -#include "core/math/constexpr.hh" - -#include "shared/entity/velocity.hh" - -#include "shared/world/dimension.hh" - -#include "client/entity/camera.hh" - -#include "client/sound/sound.hh" - -#include "client/const.hh" -#include "client/globals.hh" -#include "client/session.hh" - -void entity::listener::update(void) -{ - if(session::is_ingame()) { - const auto& velocity = globals::dimension->entities.get(globals::player).value; - const auto& position = entity::camera::position_local; - - alListener3f(AL_POSITION, position.x, position.y, position.z); - alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z); - - float orientation[6]; - orientation[0] = entity::camera::direction.x; - orientation[1] = entity::camera::direction.y; - orientation[2] = entity::camera::direction.z; - orientation[3] = DIR_UP.x; - orientation[4] = DIR_UP.y; - orientation[5] = DIR_UP.z; - - alListenerfv(AL_ORIENTATION, orientation); - } - - alListenerf(AL_GAIN, math::clamp(sound::volume_master.get_value() * 0.01f, 0.0f, 1.0f)); -} +#include "client/pch.hh" + +#include "client/entity/listener.hh" + +#include "core/config/number.hh" + +#include "core/math/constexpr.hh" + +#include "shared/entity/velocity.hh" + +#include "shared/world/dimension.hh" + +#include "client/entity/camera.hh" + +#include "client/sound/sound.hh" + +#include "client/const.hh" +#include "client/globals.hh" +#include "client/session.hh" + +void entity::listener::update(void) +{ + if(session::is_ingame()) { + const auto& velocity = globals::dimension->entities.get(globals::player).value; + const auto& position = entity::camera::position_local; + + alListener3f(AL_POSITION, position.x, position.y, position.z); + alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z); + + float orientation[6]; + orientation[0] = entity::camera::direction.x; + orientation[1] = entity::camera::direction.y; + orientation[2] = entity::camera::direction.z; + orientation[3] = DIR_UP.x; + orientation[4] = DIR_UP.y; + orientation[5] = DIR_UP.z; + + alListenerfv(AL_ORIENTATION, orientation); + } + + alListenerf(AL_GAIN, math::clamp(sound::volume_master.get_value() * 0.01f, 0.0f, 1.0f)); +} diff --git a/game/client/entity/listener.hh b/game/client/entity/listener.hh index 594cde1..817e2fd 100644 --- a/game/client/entity/listener.hh +++ b/game/client/entity/listener.hh @@ -1,6 +1,6 @@ -#pragma once - -namespace entity::listener -{ -void update(void); -} // namespace entity::listener +#pragma once + +namespace entity::listener +{ +void update(void); +} // namespace entity::listener diff --git a/game/client/entity/player_look.cc b/game/client/entity/player_look.cc index 715475b..caa367e 100644 --- a/game/client/entity/player_look.cc +++ b/game/client/entity/player_look.cc @@ -1,155 +1,155 @@ -#include "client/pch.hh" - -#include "client/entity/player_look.hh" - -#include "core/config/boolean.hh" -#include "core/config/number.hh" - -#include "core/io/config_map.hh" - -#include "core/math/angles.hh" - -#include "shared/entity/head.hh" - -#include "shared/world/dimension.hh" - -#include "client/config/gamepad_axis.hh" -#include "client/config/gamepad_button.hh" -#include "client/config/keybind.hh" - -#include "client/gui/settings.hh" - -#include "client/io/gamepad.hh" -#include "client/io/glfw.hh" - -#include "client/const.hh" -#include "client/globals.hh" -#include "client/session.hh" - -constexpr static float PITCH_MIN = -1.0f * math::radians(90.0f); -constexpr static float PITCH_MAX = +1.0f * math::radians(90.0f); - -// Mouse options -static config::Boolean mouse_raw_input(true); -static config::Unsigned mouse_sensitivity(25U, 1U, 100U); - -// Gamepad options -static config::Float gamepad_fastlook_factor(1.5f, 1.0f, 5.0f); -static config::Unsigned gamepad_accel_pitch(15U, 1U, 100U); -static config::Unsigned gamepad_accel_yaw(25U, 1U, 100U); - -// Gamepad axes -static config::GamepadAxis axis_pitch(GLFW_GAMEPAD_AXIS_LEFT_Y, false); -static config::GamepadAxis axis_yaw(GLFW_GAMEPAD_AXIS_LEFT_X, false); - -// Gamepad buttons -static config::GamepadButton button_fastlook(GLFW_GAMEPAD_BUTTON_LEFT_THUMB); - -static bool fastlook_enabled; -static glm::fvec2 last_cursor; - -static void add_angles(float pitch, float yaw) -{ - if(session::is_ingame()) { - auto& head = globals::dimension->entities.get(globals::player); - - head.angles[0] += pitch; - head.angles[1] += yaw; - head.angles[0] = math::clamp(head.angles[0], PITCH_MIN, PITCH_MAX); - head.angles = math::wrap_180(head.angles); - - // Client-side head angles are not interpolated; - // Re-assigning the previous state after the current - // state has been already modified is certainly a way - // to circumvent the interpolation applied to anything with a head - globals::dimension->entities.emplace_or_replace(globals::player, head); - } -} - -static void on_glfw_cursor_pos(const io::GlfwCursorPosEvent& event) -{ - if(io::gamepad::available && io::gamepad::active.get_value()) { - // The player is assumed to be using - // a gamepad instead of mouse and keyboard - last_cursor = event.pos; - return; - } - - if(globals::gui_screen || !session::is_ingame()) { - // UI is visible or we're not in-game - last_cursor = event.pos; - return; - } - - auto dx = -0.01f * static_cast(mouse_sensitivity.get_value()) * math::radians(event.pos.x - last_cursor.x); - auto dy = -0.01f * static_cast(mouse_sensitivity.get_value()) * math::radians(event.pos.y - last_cursor.y); - add_angles(dy, dx); - - last_cursor = event.pos; -} - -static void on_gamepad_button(const io::GamepadButtonEvent& event) -{ - if(button_fastlook.equals(event.button)) { - fastlook_enabled = event.action == GLFW_PRESS; - } -} - -void entity::player_look::init(void) -{ - globals::client_config.add_value("player_look.mouse.raw_input", mouse_raw_input); - globals::client_config.add_value("player_look.mouse.sensitivity", mouse_sensitivity); - globals::client_config.add_value("player_look.gamepad.fastlook_factor", gamepad_fastlook_factor); - globals::client_config.add_value("player_look.gamepad.accel_pitch", gamepad_accel_pitch); - globals::client_config.add_value("player_look.gamepad.accel_yaw", gamepad_accel_yaw); - globals::client_config.add_value("player_look.gp_axis.pitch", axis_pitch); - globals::client_config.add_value("player_look.gp_axis.yaw", axis_yaw); - globals::client_config.add_value("player_look.gp_button.fastlook", button_fastlook); - - settings::add_slider(0, mouse_sensitivity, settings_location::MOUSE, "player_look.mouse.sensitivity", true); - settings::add_checkbox(1, mouse_raw_input, settings_location::MOUSE, "player_look.mouse.raw_input", true); - - settings::add_slider(0, gamepad_accel_pitch, settings_location::GAMEPAD_GAMEPLAY, "player_look.gamepad.accel_pitch", false); - settings::add_slider(1, gamepad_accel_yaw, settings_location::GAMEPAD_GAMEPLAY, "player_look.gamepad.accel_yaw", false); - settings::add_gamepad_axis(2, axis_pitch, settings_location::GAMEPAD_GAMEPLAY, "player_look.gp_axis.pitch"); - settings::add_gamepad_axis(3, axis_yaw, settings_location::GAMEPAD_GAMEPLAY, "player_look.gp_axis.yaw"); - settings::add_slider( - 4, gamepad_fastlook_factor, settings_location::GAMEPAD_GAMEPLAY, "player_look.gamepad.fastlook_factor", true, "%.02f"); - settings::add_gamepad_button(5, button_fastlook, settings_location::GAMEPAD_GAMEPLAY, "player_look.gp_button.fastlook"); - - fastlook_enabled = false; - last_cursor.x = 0.5f * static_cast(globals::width); - last_cursor.y = 0.5f * static_cast(globals::height); - - globals::dispatcher.sink().connect<&on_glfw_cursor_pos>(); - globals::dispatcher.sink().connect<&on_gamepad_button>(); -} - -void entity::player_look::update_late(void) -{ - if(io::gamepad::available && io::gamepad::active.get_value() && !globals::gui_screen) { - auto pitch_value = axis_pitch.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); - auto yaw_value = axis_yaw.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); - - if(fastlook_enabled) { - // Fastlook allows the camera to - // rotate quicker when a button is held down - pitch_value *= gamepad_fastlook_factor.get_value(); - yaw_value *= gamepad_fastlook_factor.get_value(); - } - - pitch_value *= 0.001f * static_cast(gamepad_accel_pitch.get_value()); - yaw_value *= 0.001f * static_cast(gamepad_accel_yaw.get_value()); - - add_angles(pitch_value, yaw_value); - } - - if(!globals::gui_screen && session::is_ingame()) { - glfwSetInputMode(globals::window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); - glfwSetInputMode(globals::window, GLFW_RAW_MOUSE_MOTION, mouse_raw_input.get_value()); - } - else { - glfwSetInputMode(globals::window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); - glfwSetInputMode(globals::window, GLFW_RAW_MOUSE_MOTION, false); - } -} +#include "client/pch.hh" + +#include "client/entity/player_look.hh" + +#include "core/config/boolean.hh" +#include "core/config/number.hh" + +#include "core/io/config_map.hh" + +#include "core/math/angles.hh" + +#include "shared/entity/head.hh" + +#include "shared/world/dimension.hh" + +#include "client/config/gamepad_axis.hh" +#include "client/config/gamepad_button.hh" +#include "client/config/keybind.hh" + +#include "client/gui/settings.hh" + +#include "client/io/gamepad.hh" +#include "client/io/glfw.hh" + +#include "client/const.hh" +#include "client/globals.hh" +#include "client/session.hh" + +constexpr static float PITCH_MIN = -1.0f * math::radians(90.0f); +constexpr static float PITCH_MAX = +1.0f * math::radians(90.0f); + +// Mouse options +static config::Boolean mouse_raw_input(true); +static config::Unsigned mouse_sensitivity(25U, 1U, 100U); + +// Gamepad options +static config::Float gamepad_fastlook_factor(1.5f, 1.0f, 5.0f); +static config::Unsigned gamepad_accel_pitch(15U, 1U, 100U); +static config::Unsigned gamepad_accel_yaw(25U, 1U, 100U); + +// Gamepad axes +static config::GamepadAxis axis_pitch(GLFW_GAMEPAD_AXIS_LEFT_Y, false); +static config::GamepadAxis axis_yaw(GLFW_GAMEPAD_AXIS_LEFT_X, false); + +// Gamepad buttons +static config::GamepadButton button_fastlook(GLFW_GAMEPAD_BUTTON_LEFT_THUMB); + +static bool fastlook_enabled; +static glm::fvec2 last_cursor; + +static void add_angles(float pitch, float yaw) +{ + if(session::is_ingame()) { + auto& head = globals::dimension->entities.get(globals::player); + + head.angles[0] += pitch; + head.angles[1] += yaw; + head.angles[0] = math::clamp(head.angles[0], PITCH_MIN, PITCH_MAX); + head.angles = math::wrap_180(head.angles); + + // Client-side head angles are not interpolated; + // Re-assigning the previous state after the current + // state has been already modified is certainly a way + // to circumvent the interpolation applied to anything with a head + globals::dimension->entities.emplace_or_replace(globals::player, head); + } +} + +static void on_glfw_cursor_pos(const io::GlfwCursorPosEvent& event) +{ + if(io::gamepad::available && io::gamepad::active.get_value()) { + // The player is assumed to be using + // a gamepad instead of mouse and keyboard + last_cursor = event.pos; + return; + } + + if(globals::gui_screen || !session::is_ingame()) { + // UI is visible or we're not in-game + last_cursor = event.pos; + return; + } + + auto dx = -0.01f * static_cast(mouse_sensitivity.get_value()) * math::radians(event.pos.x - last_cursor.x); + auto dy = -0.01f * static_cast(mouse_sensitivity.get_value()) * math::radians(event.pos.y - last_cursor.y); + add_angles(dy, dx); + + last_cursor = event.pos; +} + +static void on_gamepad_button(const io::GamepadButtonEvent& event) +{ + if(button_fastlook.equals(event.button)) { + fastlook_enabled = event.action == GLFW_PRESS; + } +} + +void entity::player_look::init(void) +{ + globals::client_config.add_value("player_look.mouse.raw_input", mouse_raw_input); + globals::client_config.add_value("player_look.mouse.sensitivity", mouse_sensitivity); + globals::client_config.add_value("player_look.gamepad.fastlook_factor", gamepad_fastlook_factor); + globals::client_config.add_value("player_look.gamepad.accel_pitch", gamepad_accel_pitch); + globals::client_config.add_value("player_look.gamepad.accel_yaw", gamepad_accel_yaw); + globals::client_config.add_value("player_look.gp_axis.pitch", axis_pitch); + globals::client_config.add_value("player_look.gp_axis.yaw", axis_yaw); + globals::client_config.add_value("player_look.gp_button.fastlook", button_fastlook); + + settings::add_slider(0, mouse_sensitivity, settings_location::MOUSE, "player_look.mouse.sensitivity", true); + settings::add_checkbox(1, mouse_raw_input, settings_location::MOUSE, "player_look.mouse.raw_input", true); + + settings::add_slider(0, gamepad_accel_pitch, settings_location::GAMEPAD_GAMEPLAY, "player_look.gamepad.accel_pitch", false); + settings::add_slider(1, gamepad_accel_yaw, settings_location::GAMEPAD_GAMEPLAY, "player_look.gamepad.accel_yaw", false); + settings::add_gamepad_axis(2, axis_pitch, settings_location::GAMEPAD_GAMEPLAY, "player_look.gp_axis.pitch"); + settings::add_gamepad_axis(3, axis_yaw, settings_location::GAMEPAD_GAMEPLAY, "player_look.gp_axis.yaw"); + settings::add_slider(4, gamepad_fastlook_factor, settings_location::GAMEPAD_GAMEPLAY, "player_look.gamepad.fastlook_factor", true, + "%.02f"); + settings::add_gamepad_button(5, button_fastlook, settings_location::GAMEPAD_GAMEPLAY, "player_look.gp_button.fastlook"); + + fastlook_enabled = false; + last_cursor.x = 0.5f * static_cast(globals::width); + last_cursor.y = 0.5f * static_cast(globals::height); + + globals::dispatcher.sink().connect<&on_glfw_cursor_pos>(); + globals::dispatcher.sink().connect<&on_gamepad_button>(); +} + +void entity::player_look::update_late(void) +{ + if(io::gamepad::available && io::gamepad::active.get_value() && !globals::gui_screen) { + auto pitch_value = axis_pitch.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); + auto yaw_value = axis_yaw.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); + + if(fastlook_enabled) { + // Fastlook allows the camera to + // rotate quicker when a button is held down + pitch_value *= gamepad_fastlook_factor.get_value(); + yaw_value *= gamepad_fastlook_factor.get_value(); + } + + pitch_value *= 0.001f * static_cast(gamepad_accel_pitch.get_value()); + yaw_value *= 0.001f * static_cast(gamepad_accel_yaw.get_value()); + + add_angles(pitch_value, yaw_value); + } + + if(!globals::gui_screen && session::is_ingame()) { + glfwSetInputMode(globals::window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); + glfwSetInputMode(globals::window, GLFW_RAW_MOUSE_MOTION, mouse_raw_input.get_value()); + } + else { + glfwSetInputMode(globals::window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + glfwSetInputMode(globals::window, GLFW_RAW_MOUSE_MOTION, false); + } +} diff --git a/game/client/entity/player_look.hh b/game/client/entity/player_look.hh index 0ae18db..b347031 100644 --- a/game/client/entity/player_look.hh +++ b/game/client/entity/player_look.hh @@ -1,7 +1,7 @@ -#pragma once - -namespace entity::player_look -{ -void init(void); -void update_late(void); -} // namespace entity::player_look +#pragma once + +namespace entity::player_look +{ +void init(void); +void update_late(void); +} // namespace entity::player_look diff --git a/game/client/entity/player_move.cc b/game/client/entity/player_move.cc index fb49754..2570780 100644 --- a/game/client/entity/player_move.cc +++ b/game/client/entity/player_move.cc @@ -1,298 +1,298 @@ -#include "client/pch.hh" - -#include "client/entity/player_move.hh" - -#include "core/config/boolean.hh" -#include "core/config/number.hh" - -#include "core/io/config_map.hh" - -#include "core/math/angles.hh" -#include "core/math/constexpr.hh" - -#include "shared/entity/grounded.hh" -#include "shared/entity/head.hh" -#include "shared/entity/transform.hh" -#include "shared/entity/velocity.hh" - -#include "shared/world/dimension.hh" - -#include "client/config/gamepad_axis.hh" -#include "client/config/gamepad_button.hh" -#include "client/config/keybind.hh" - -#include "client/gui/gui_screen.hh" -#include "client/gui/settings.hh" -#include "client/gui/status_lines.hh" - -#include "client/io/gamepad.hh" - -#include "client/sound/sound.hh" - -#include "client/world/voxel_sounds.hh" - -#include "client/const.hh" -#include "client/globals.hh" -#include "client/session.hh" -#include "client/toggles.hh" - -constexpr static std::uint64_t PMOVE_JUMP_COOLDOWN = 500000; // 0.5 seconds - -constexpr static float PMOVE_FOOTSTEP_SIZE = 2.0f; - -// Movement keys -static config::KeyBind key_move_forward(GLFW_KEY_W); -static config::KeyBind key_move_back(GLFW_KEY_S); -static config::KeyBind key_move_left(GLFW_KEY_A); -static config::KeyBind key_move_right(GLFW_KEY_D); -static config::KeyBind key_move_down(GLFW_KEY_LEFT_SHIFT); -static config::KeyBind key_move_up(GLFW_KEY_SPACE); - -// Movement gamepad axes -static config::GamepadAxis axis_move_forward(GLFW_GAMEPAD_AXIS_RIGHT_X, false); -static config::GamepadAxis axis_move_sideways(GLFW_GAMEPAD_AXIS_RIGHT_Y, false); - -// Movement gamepad buttons -static config::GamepadButton button_move_down(GLFW_GAMEPAD_BUTTON_DPAD_DOWN); -static config::GamepadButton button_move_up(GLFW_GAMEPAD_BUTTON_DPAD_UP); - -// General movement options -static config::Boolean enable_speedometer(true); - -static glm::fvec3 movement_direction; - -static std::uint64_t next_jump_us; -static float speedometer_value; -static float footsteps_distance; - -static std::mt19937_64 pitch_random; -static std::uniform_real_distribution pitch_distrib; - -// Quake III's PM_Accelerate-ish function used for -// conventional (gravity-affected non-flight) movement -static glm::fvec3 pm_accelerate(const glm::fvec3& wishdir, const glm::fvec3& velocity, float wishspeed, float accel) -{ - auto current_speed = glm::dot(velocity, wishdir); - auto add_speed = wishspeed - current_speed; - - if(add_speed <= 0.0f) { - // Not accelerating - return velocity; - } - - auto accel_speed = math::min(add_speed, accel * globals::fixed_frametime * wishspeed); - - auto result = glm::fvec3(velocity); - result.x += accel_speed * wishdir.x; - result.z += accel_speed * wishdir.z; - return result; -} - -// Conventional movement - velocity update when not on the ground -static glm::fvec3 pm_air_move(const glm::fvec3& wishdir, const glm::fvec3& velocity) -{ - return pm_accelerate(wishdir, velocity, PMOVE_ACCELERATION_AIR, PMOVE_MAX_SPEED_AIR); -} - -// Conventional movement - velocity uodate when on the ground -static glm::fvec3 pm_ground_move(const glm::fvec3& wishdir, const glm::fvec3& velocity) -{ - if(auto speed = glm::length(velocity)) { - auto speed_drop = speed * PMOVE_FRICTION_GROUND * globals::fixed_frametime; - auto speed_factor = math::max(speed - speed_drop, 0.0f) / speed; - return pm_accelerate(wishdir, velocity * speed_factor, PMOVE_ACCELERATION_GROUND, PMOVE_MAX_SPEED_GROUND); - } - - return pm_accelerate(wishdir, velocity, PMOVE_ACCELERATION_GROUND, PMOVE_MAX_SPEED_GROUND); -} - -// A simpler minecraft-like acceleration model -// used whenever the TOGGLE_PM_FLIGHT is enabled -static glm::fvec3 pm_flight_move(const glm::fvec3& wishdir) -{ - // FIXME: make it smoother - return wishdir * PMOVE_MAX_SPEED_AIR; -} - -void entity::player_move::init(void) -{ - movement_direction = ZERO_VEC3; - - next_jump_us = 0x0000000000000000U; - speedometer_value = 0.0f; - footsteps_distance = 0.0f; - - // UNDONE: make this a separate subsystem - pitch_random.seed(std::random_device()()); - pitch_distrib = std::uniform_real_distribution(0.9f, 1.1f); - - globals::client_config.add_value("player_move.key.forward", key_move_forward); - globals::client_config.add_value("player_move.key.back", key_move_back); - globals::client_config.add_value("player_move.key.left", key_move_left); - globals::client_config.add_value("player_move.key.right", key_move_right); - globals::client_config.add_value("player_move.key.down", key_move_down); - globals::client_config.add_value("player_move.key.up", key_move_up); - globals::client_config.add_value("player_move.gp_axis.move_forward", axis_move_forward); - globals::client_config.add_value("player_move.gp_axis.move_sideways", axis_move_sideways); - globals::client_config.add_value("player_move.gp_button.move_down", button_move_down); - globals::client_config.add_value("player_move.gp_button.move_up", button_move_up); - globals::client_config.add_value("player_move.enable_speedometer", enable_speedometer); - - settings::add_keybind(1, key_move_forward, settings_location::KEYBOARD_MOVEMENT, "player_move.key.forward"); - settings::add_keybind(2, key_move_back, settings_location::KEYBOARD_MOVEMENT, "player_move.key.back"); - settings::add_keybind(3, key_move_left, settings_location::KEYBOARD_MOVEMENT, "player_move.key.left"); - settings::add_keybind(4, key_move_right, settings_location::KEYBOARD_MOVEMENT, "player_move.key.right"); - settings::add_keybind(5, key_move_down, settings_location::KEYBOARD_MOVEMENT, "player_move.key.down"); - settings::add_keybind(6, key_move_up, settings_location::KEYBOARD_MOVEMENT, "player_move.key.up"); - - settings::add_gamepad_axis(0, axis_move_forward, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_axis.move_forward"); - settings::add_gamepad_axis(1, axis_move_sideways, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_axis.move_sideways"); - settings::add_gamepad_button(2, button_move_down, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_button.move_down"); - settings::add_gamepad_button(3, button_move_up, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_button.move_up"); - - settings::add_checkbox(2, enable_speedometer, settings_location::VIDEO_GUI, "player_move.enable_speedometer", true); -} - -void entity::player_move::fixed_update(void) -{ - const auto& head = globals::dimension->entities.get(globals::player); - auto& transform = globals::dimension->entities.get(globals::player); - auto& velocity = globals::dimension->entities.get(globals::player); - - // Interpolation - preserve current component states - globals::dimension->entities.emplace_or_replace(globals::player, transform); - - glm::fvec3 forward, right; - math::vectors(glm::fvec3(0.0f, head.angles[1], 0.0f), &forward, &right, nullptr); - - glm::fvec3 wishdir = ZERO_VEC3; - glm::fvec3 movevars = glm::fvec3(movement_direction.x, 0.0f, movement_direction.z); - wishdir.x = glm::dot(movevars, right); - wishdir.z = glm::dot(movevars, forward); - - if(toggles::get(TOGGLE_PM_FLIGHT)) { - velocity.value = pm_flight_move(glm::fvec3(wishdir.x, movement_direction.y, wishdir.z)); - return; - } - - auto grounded = globals::dimension->entities.try_get(globals::player); - auto velocity_horizontal = glm::fvec3(velocity.value.x, 0.0f, velocity.value.z); - - if(grounded) { - auto new_velocity = pm_ground_move(wishdir, velocity_horizontal); - velocity.value.x = new_velocity.x; - velocity.value.z = new_velocity.z; - - auto new_speed = glm::length(new_velocity); - - if(new_speed > 0.01f) { - footsteps_distance += globals::fixed_frametime * new_speed; - } - else { - footsteps_distance = 0.0f; - } - - if(footsteps_distance >= PMOVE_FOOTSTEP_SIZE) { - if(auto effect = world::voxel_sounds::get_footsteps(grounded->surface)) { - sound::play_player(effect, false, pitch_distrib(pitch_random)); - } - - footsteps_distance = 0.0f; - } - } - else { - auto new_velocity = pm_air_move(wishdir, velocity_horizontal); - velocity.value.x = new_velocity.x; - velocity.value.z = new_velocity.z; - } - - if(movement_direction.y == 0.0f) { - // Allow players to queue bunny-jumps by quickly - // releasing and pressing the jump key again without a cooldown - next_jump_us = 0x0000000000000000U; - return; - } - - if(grounded && (movement_direction.y > 0.0f) && (globals::curtime >= next_jump_us)) { - velocity.value.y = -PMOVE_JUMP_FORCE * globals::dimension->get_gravity(); - - auto new_speed = glm::length(glm::fvec2(velocity.value.x, velocity.value.z)); - auto new_speed_text = std::format("{:.02f} M/S", new_speed); - auto speed_change = new_speed - speedometer_value; - - speedometer_value = new_speed; - - next_jump_us = globals::curtime + PMOVE_JUMP_COOLDOWN; - - if(enable_speedometer.get_value()) { - if(math::abs(speed_change) < 0.01f) { - // No considerable speed increase within - // the precision we use to draw the speedometer - gui::status_lines::set(gui::STATUS_DEBUG, new_speed_text, ImVec4(0.7f, 0.7f, 0.7f, 1.0f), 1.0f); - } - else if(speed_change < 0.0f) { - // Speed change is negative, we are actively - // slowing down; use the red color for the status line - gui::status_lines::set(gui::STATUS_DEBUG, new_speed_text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 1.0f); - } - else { - // Speed change is positive, we are actively - // speeding up; use the green color for the status line - gui::status_lines::set(gui::STATUS_DEBUG, new_speed_text, ImVec4(0.0f, 1.0f, 0.0f, 1.0f), 1.0f); - } - } - - if(auto effect = world::voxel_sounds::get_footsteps(grounded->surface)) { - sound::play_player(effect, false, 1.0f); - } - } -} - -void entity::player_move::update_late(void) -{ - movement_direction = ZERO_VEC3; - - if(globals::gui_screen || !session::is_ingame()) { - // We're either disconnected or have the - // UI opened up; anyways we shouldn't move - return; - } - - if(io::gamepad::available && io::gamepad::active.get_value()) { - if(button_move_down.is_pressed(io::gamepad::state)) { - movement_direction += DIR_DOWN; - } - - if(button_move_up.is_pressed(io::gamepad::state)) { - movement_direction += DIR_UP; - } - - movement_direction.x += axis_move_sideways.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); - movement_direction.z -= axis_move_forward.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); - } - else { - if(GLFW_PRESS == glfwGetKey(globals::window, key_move_forward.get_key())) { - movement_direction += DIR_FORWARD; - } - - if(GLFW_PRESS == glfwGetKey(globals::window, key_move_back.get_key())) { - movement_direction += DIR_BACK; - } - - if(GLFW_PRESS == glfwGetKey(globals::window, key_move_left.get_key())) { - movement_direction += DIR_LEFT; - } - - if(GLFW_PRESS == glfwGetKey(globals::window, key_move_right.get_key())) { - movement_direction += DIR_RIGHT; - } - - if(GLFW_PRESS == glfwGetKey(globals::window, key_move_down.get_key())) { - movement_direction += DIR_DOWN; - } - - if(GLFW_PRESS == glfwGetKey(globals::window, key_move_up.get_key())) { - movement_direction += DIR_UP; - } - } -} +#include "client/pch.hh" + +#include "client/entity/player_move.hh" + +#include "core/config/boolean.hh" +#include "core/config/number.hh" + +#include "core/io/config_map.hh" + +#include "core/math/angles.hh" +#include "core/math/constexpr.hh" + +#include "shared/entity/grounded.hh" +#include "shared/entity/head.hh" +#include "shared/entity/transform.hh" +#include "shared/entity/velocity.hh" + +#include "shared/world/dimension.hh" + +#include "client/config/gamepad_axis.hh" +#include "client/config/gamepad_button.hh" +#include "client/config/keybind.hh" + +#include "client/gui/gui_screen.hh" +#include "client/gui/settings.hh" +#include "client/gui/status_lines.hh" + +#include "client/io/gamepad.hh" + +#include "client/sound/sound.hh" + +#include "client/world/voxel_sounds.hh" + +#include "client/const.hh" +#include "client/globals.hh" +#include "client/session.hh" +#include "client/toggles.hh" + +constexpr static std::uint64_t PMOVE_JUMP_COOLDOWN = 500000; // 0.5 seconds + +constexpr static float PMOVE_FOOTSTEP_SIZE = 2.0f; + +// Movement keys +static config::KeyBind key_move_forward(GLFW_KEY_W); +static config::KeyBind key_move_back(GLFW_KEY_S); +static config::KeyBind key_move_left(GLFW_KEY_A); +static config::KeyBind key_move_right(GLFW_KEY_D); +static config::KeyBind key_move_down(GLFW_KEY_LEFT_SHIFT); +static config::KeyBind key_move_up(GLFW_KEY_SPACE); + +// Movement gamepad axes +static config::GamepadAxis axis_move_forward(GLFW_GAMEPAD_AXIS_RIGHT_X, false); +static config::GamepadAxis axis_move_sideways(GLFW_GAMEPAD_AXIS_RIGHT_Y, false); + +// Movement gamepad buttons +static config::GamepadButton button_move_down(GLFW_GAMEPAD_BUTTON_DPAD_DOWN); +static config::GamepadButton button_move_up(GLFW_GAMEPAD_BUTTON_DPAD_UP); + +// General movement options +static config::Boolean enable_speedometer(true); + +static glm::fvec3 movement_direction; + +static std::uint64_t next_jump_us; +static float speedometer_value; +static float footsteps_distance; + +static std::mt19937_64 pitch_random; +static std::uniform_real_distribution pitch_distrib; + +// Quake III's PM_Accelerate-ish function used for +// conventional (gravity-affected non-flight) movement +static glm::fvec3 pm_accelerate(const glm::fvec3& wishdir, const glm::fvec3& velocity, float wishspeed, float accel) +{ + auto current_speed = glm::dot(velocity, wishdir); + auto add_speed = wishspeed - current_speed; + + if(add_speed <= 0.0f) { + // Not accelerating + return velocity; + } + + auto accel_speed = math::min(add_speed, accel * globals::fixed_frametime * wishspeed); + + auto result = glm::fvec3(velocity); + result.x += accel_speed * wishdir.x; + result.z += accel_speed * wishdir.z; + return result; +} + +// Conventional movement - velocity update when not on the ground +static glm::fvec3 pm_air_move(const glm::fvec3& wishdir, const glm::fvec3& velocity) +{ + return pm_accelerate(wishdir, velocity, PMOVE_ACCELERATION_AIR, PMOVE_MAX_SPEED_AIR); +} + +// Conventional movement - velocity uodate when on the ground +static glm::fvec3 pm_ground_move(const glm::fvec3& wishdir, const glm::fvec3& velocity) +{ + if(auto speed = glm::length(velocity)) { + auto speed_drop = speed * PMOVE_FRICTION_GROUND * globals::fixed_frametime; + auto speed_factor = math::max(speed - speed_drop, 0.0f) / speed; + return pm_accelerate(wishdir, velocity * speed_factor, PMOVE_ACCELERATION_GROUND, PMOVE_MAX_SPEED_GROUND); + } + + return pm_accelerate(wishdir, velocity, PMOVE_ACCELERATION_GROUND, PMOVE_MAX_SPEED_GROUND); +} + +// A simpler minecraft-like acceleration model +// used whenever the TOGGLE_PM_FLIGHT is enabled +static glm::fvec3 pm_flight_move(const glm::fvec3& wishdir) +{ + // FIXME: make it smoother + return wishdir * PMOVE_MAX_SPEED_AIR; +} + +void entity::player_move::init(void) +{ + movement_direction = ZERO_VEC3; + + next_jump_us = 0x0000000000000000U; + speedometer_value = 0.0f; + footsteps_distance = 0.0f; + + // UNDONE: make this a separate subsystem + pitch_random.seed(std::random_device()()); + pitch_distrib = std::uniform_real_distribution(0.9f, 1.1f); + + globals::client_config.add_value("player_move.key.forward", key_move_forward); + globals::client_config.add_value("player_move.key.back", key_move_back); + globals::client_config.add_value("player_move.key.left", key_move_left); + globals::client_config.add_value("player_move.key.right", key_move_right); + globals::client_config.add_value("player_move.key.down", key_move_down); + globals::client_config.add_value("player_move.key.up", key_move_up); + globals::client_config.add_value("player_move.gp_axis.move_forward", axis_move_forward); + globals::client_config.add_value("player_move.gp_axis.move_sideways", axis_move_sideways); + globals::client_config.add_value("player_move.gp_button.move_down", button_move_down); + globals::client_config.add_value("player_move.gp_button.move_up", button_move_up); + globals::client_config.add_value("player_move.enable_speedometer", enable_speedometer); + + settings::add_keybind(1, key_move_forward, settings_location::KEYBOARD_MOVEMENT, "player_move.key.forward"); + settings::add_keybind(2, key_move_back, settings_location::KEYBOARD_MOVEMENT, "player_move.key.back"); + settings::add_keybind(3, key_move_left, settings_location::KEYBOARD_MOVEMENT, "player_move.key.left"); + settings::add_keybind(4, key_move_right, settings_location::KEYBOARD_MOVEMENT, "player_move.key.right"); + settings::add_keybind(5, key_move_down, settings_location::KEYBOARD_MOVEMENT, "player_move.key.down"); + settings::add_keybind(6, key_move_up, settings_location::KEYBOARD_MOVEMENT, "player_move.key.up"); + + settings::add_gamepad_axis(0, axis_move_forward, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_axis.move_forward"); + settings::add_gamepad_axis(1, axis_move_sideways, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_axis.move_sideways"); + settings::add_gamepad_button(2, button_move_down, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_button.move_down"); + settings::add_gamepad_button(3, button_move_up, settings_location::GAMEPAD_MOVEMENT, "player_move.gp_button.move_up"); + + settings::add_checkbox(2, enable_speedometer, settings_location::VIDEO_GUI, "player_move.enable_speedometer", true); +} + +void entity::player_move::fixed_update(void) +{ + const auto& head = globals::dimension->entities.get(globals::player); + auto& transform = globals::dimension->entities.get(globals::player); + auto& velocity = globals::dimension->entities.get(globals::player); + + // Interpolation - preserve current component states + globals::dimension->entities.emplace_or_replace(globals::player, transform); + + glm::fvec3 forward, right; + math::vectors(glm::fvec3(0.0f, head.angles[1], 0.0f), &forward, &right, nullptr); + + glm::fvec3 wishdir = ZERO_VEC3; + glm::fvec3 movevars = glm::fvec3(movement_direction.x, 0.0f, movement_direction.z); + wishdir.x = glm::dot(movevars, right); + wishdir.z = glm::dot(movevars, forward); + + if(toggles::get(TOGGLE_PM_FLIGHT)) { + velocity.value = pm_flight_move(glm::fvec3(wishdir.x, movement_direction.y, wishdir.z)); + return; + } + + auto grounded = globals::dimension->entities.try_get(globals::player); + auto velocity_horizontal = glm::fvec3(velocity.value.x, 0.0f, velocity.value.z); + + if(grounded) { + auto new_velocity = pm_ground_move(wishdir, velocity_horizontal); + velocity.value.x = new_velocity.x; + velocity.value.z = new_velocity.z; + + auto new_speed = glm::length(new_velocity); + + if(new_speed > 0.01f) { + footsteps_distance += globals::fixed_frametime * new_speed; + } + else { + footsteps_distance = 0.0f; + } + + if(footsteps_distance >= PMOVE_FOOTSTEP_SIZE) { + if(auto effect = world::voxel_sounds::get_footsteps(grounded->surface)) { + sound::play_player(effect, false, pitch_distrib(pitch_random)); + } + + footsteps_distance = 0.0f; + } + } + else { + auto new_velocity = pm_air_move(wishdir, velocity_horizontal); + velocity.value.x = new_velocity.x; + velocity.value.z = new_velocity.z; + } + + if(movement_direction.y == 0.0f) { + // Allow players to queue bunny-jumps by quickly + // releasing and pressing the jump key again without a cooldown + next_jump_us = 0x0000000000000000U; + return; + } + + if(grounded && (movement_direction.y > 0.0f) && (globals::curtime >= next_jump_us)) { + velocity.value.y = -PMOVE_JUMP_FORCE * globals::dimension->get_gravity(); + + auto new_speed = glm::length(glm::fvec2(velocity.value.x, velocity.value.z)); + auto new_speed_text = std::format("{:.02f} M/S", new_speed); + auto speed_change = new_speed - speedometer_value; + + speedometer_value = new_speed; + + next_jump_us = globals::curtime + PMOVE_JUMP_COOLDOWN; + + if(enable_speedometer.get_value()) { + if(math::abs(speed_change) < 0.01f) { + // No considerable speed increase within + // the precision we use to draw the speedometer + gui::status_lines::set(gui::STATUS_DEBUG, new_speed_text, ImVec4(0.7f, 0.7f, 0.7f, 1.0f), 1.0f); + } + else if(speed_change < 0.0f) { + // Speed change is negative, we are actively + // slowing down; use the red color for the status line + gui::status_lines::set(gui::STATUS_DEBUG, new_speed_text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f), 1.0f); + } + else { + // Speed change is positive, we are actively + // speeding up; use the green color for the status line + gui::status_lines::set(gui::STATUS_DEBUG, new_speed_text, ImVec4(0.0f, 1.0f, 0.0f, 1.0f), 1.0f); + } + } + + if(auto effect = world::voxel_sounds::get_footsteps(grounded->surface)) { + sound::play_player(effect, false, 1.0f); + } + } +} + +void entity::player_move::update_late(void) +{ + movement_direction = ZERO_VEC3; + + if(globals::gui_screen || !session::is_ingame()) { + // We're either disconnected or have the + // UI opened up; anyways we shouldn't move + return; + } + + if(io::gamepad::available && io::gamepad::active.get_value()) { + if(button_move_down.is_pressed(io::gamepad::state)) { + movement_direction += DIR_DOWN; + } + + if(button_move_up.is_pressed(io::gamepad::state)) { + movement_direction += DIR_UP; + } + + movement_direction.x += axis_move_sideways.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); + movement_direction.z -= axis_move_forward.get_value(io::gamepad::state, io::gamepad::deadzone.get_value()); + } + else { + if(GLFW_PRESS == glfwGetKey(globals::window, key_move_forward.get_key())) { + movement_direction += DIR_FORWARD; + } + + if(GLFW_PRESS == glfwGetKey(globals::window, key_move_back.get_key())) { + movement_direction += DIR_BACK; + } + + if(GLFW_PRESS == glfwGetKey(globals::window, key_move_left.get_key())) { + movement_direction += DIR_LEFT; + } + + if(GLFW_PRESS == glfwGetKey(globals::window, key_move_right.get_key())) { + movement_direction += DIR_RIGHT; + } + + if(GLFW_PRESS == glfwGetKey(globals::window, key_move_down.get_key())) { + movement_direction += DIR_DOWN; + } + + if(GLFW_PRESS == glfwGetKey(globals::window, key_move_up.get_key())) { + movement_direction += DIR_UP; + } + } +} diff --git a/game/client/entity/player_move.hh b/game/client/entity/player_move.hh index 8c033cc..8026acf 100644 --- a/game/client/entity/player_move.hh +++ b/game/client/entity/player_move.hh @@ -1,15 +1,15 @@ -#pragma once - -constexpr static float PMOVE_MAX_SPEED_AIR = 16.0f; -constexpr static float PMOVE_MAX_SPEED_GROUND = 8.0f; -constexpr static float PMOVE_ACCELERATION_AIR = 3.0f; -constexpr static float PMOVE_ACCELERATION_GROUND = 6.0f; -constexpr static float PMOVE_FRICTION_GROUND = 10.0f; -constexpr static float PMOVE_JUMP_FORCE = 0.275f; - -namespace entity::player_move -{ -void init(void); -void fixed_update(void); -void update_late(void); -} // namespace entity::player_move +#pragma once + +constexpr static float PMOVE_MAX_SPEED_AIR = 16.0f; +constexpr static float PMOVE_MAX_SPEED_GROUND = 8.0f; +constexpr static float PMOVE_ACCELERATION_AIR = 3.0f; +constexpr static float PMOVE_ACCELERATION_GROUND = 6.0f; +constexpr static float PMOVE_FRICTION_GROUND = 10.0f; +constexpr static float PMOVE_JUMP_FORCE = 0.275f; + +namespace entity::player_move +{ +void init(void); +void fixed_update(void); +void update_late(void); +} // namespace entity::player_move diff --git a/game/client/entity/sound_emitter.cc b/game/client/entity/sound_emitter.cc index eeb7294..c2a93a1 100644 --- a/game/client/entity/sound_emitter.cc +++ b/game/client/entity/sound_emitter.cc @@ -1,63 +1,63 @@ -#include "client/pch.hh" - -#include "client/entity/sound_emitter.hh" - -#include "core/config/number.hh" - -#include "core/math/constexpr.hh" - -#include "shared/entity/transform.hh" -#include "shared/entity/velocity.hh" - -#include "shared/world/dimension.hh" - -#include "shared/coord.hh" - -#include "client/entity/camera.hh" - -#include "client/sound/sound.hh" - -#include "client/globals.hh" - -entity::SoundEmitter::SoundEmitter(void) -{ - alGenSources(1, &source); - sound = nullptr; -} - -entity::SoundEmitter::~SoundEmitter(void) -{ - alSourceStop(source); - alDeleteSources(1, &source); -} - -void entity::SoundEmitter::update(void) -{ - if(globals::dimension) { - const auto view = globals::dimension->entities.view(); - - const auto& pivot = entity::camera::position_chunk; - const auto gain = math::clamp(sound::volume_effects.get_value() * 0.01f, 0.0f, 1.0f); - - for(const auto [entity, emitter] : view.each()) { - alSourcef(emitter.source, AL_GAIN, gain); - - if(const auto transform = globals::dimension->entities.try_get(entity)) { - auto position = coord::to_relative(pivot, transform->chunk, transform->local); - alSource3f(emitter.source, AL_POSITION, position.x, position.y, position.z); - } - - if(const auto velocity = globals::dimension->entities.try_get(entity)) { - alSource3f(emitter.source, AL_VELOCITY, velocity->value.x, velocity->value.y, velocity->value.z); - } - - ALint source_state; - alGetSourcei(emitter.source, AL_SOURCE_STATE, &source_state); - - if(source_state == AL_STOPPED) { - alSourceRewind(emitter.source); - emitter.sound = nullptr; - } - } - } -} +#include "client/pch.hh" + +#include "client/entity/sound_emitter.hh" + +#include "core/config/number.hh" + +#include "core/math/constexpr.hh" + +#include "shared/entity/transform.hh" +#include "shared/entity/velocity.hh" + +#include "shared/world/dimension.hh" + +#include "shared/coord.hh" + +#include "client/entity/camera.hh" + +#include "client/sound/sound.hh" + +#include "client/globals.hh" + +entity::SoundEmitter::SoundEmitter(void) +{ + alGenSources(1, &source); + sound = nullptr; +} + +entity::SoundEmitter::~SoundEmitter(void) +{ + alSourceStop(source); + alDeleteSources(1, &source); +} + +void entity::SoundEmitter::update(void) +{ + if(globals::dimension) { + const auto view = globals::dimension->entities.view(); + + const auto& pivot = entity::camera::position_chunk; + const auto gain = math::clamp(sound::volume_effects.get_value() * 0.01f, 0.0f, 1.0f); + + for(const auto [entity, emitter] : view.each()) { + alSourcef(emitter.source, AL_GAIN, gain); + + if(const auto transform = globals::dimension->entities.try_get(entity)) { + auto position = coord::to_relative(pivot, transform->chunk, transform->local); + alSource3f(emitter.source, AL_POSITION, position.x, position.y, position.z); + } + + if(const auto velocity = globals::dimension->entities.try_get(entity)) { + alSource3f(emitter.source, AL_VELOCITY, velocity->value.x, velocity->value.y, velocity->value.z); + } + + ALint source_state; + alGetSourcei(emitter.source, AL_SOURCE_STATE, &source_state); + + if(source_state == AL_STOPPED) { + alSourceRewind(emitter.source); + emitter.sound = nullptr; + } + } + } +} diff --git a/game/client/entity/sound_emitter.hh b/game/client/entity/sound_emitter.hh index 72a3f74..14093db 100644 --- a/game/client/entity/sound_emitter.hh +++ b/game/client/entity/sound_emitter.hh @@ -1,20 +1,20 @@ -#pragma once - -#include "core/resource/resource.hh" - -struct SoundEffect; - -namespace entity -{ -struct SoundEmitter final { - resource_ptr sound; - ALuint source; - -public: - explicit SoundEmitter(void); - virtual ~SoundEmitter(void); - -public: - static void update(void); -}; -} // namespace entity +#pragma once + +#include "core/resource/resource.hh" + +struct SoundEffect; + +namespace entity +{ +struct SoundEmitter final { + resource_ptr sound; + ALuint source; + +public: + explicit SoundEmitter(void); + virtual ~SoundEmitter(void); + +public: + static void update(void); +}; +} // namespace entity diff --git a/game/client/experiments.cc b/game/client/experiments.cc index 247bce9..2b9fe89 100644 --- a/game/client/experiments.cc +++ b/game/client/experiments.cc @@ -1,81 +1,81 @@ -#include "client/pch.hh" - -#include "client/experiments.hh" - -#include "shared/world/dimension.hh" -#include "shared/world/item_registry.hh" - -#include "shared/game_items.hh" -#include "shared/game_voxels.hh" - -#include "client/gui/chat.hh" -#include "client/gui/hotbar.hh" -#include "client/gui/status_lines.hh" - -#include "client/io/glfw.hh" - -#include "client/world/player_target.hh" - -#include "client/globals.hh" -#include "client/session.hh" - -static void on_glfw_mouse_button(const io::GlfwMouseButtonEvent& event) -{ - if(!globals::gui_screen && session::is_ingame()) { - if((event.action == GLFW_PRESS) && (world::player_target::voxel != NULL_VOXEL_ID)) { - if(event.button == GLFW_MOUSE_BUTTON_LEFT) { - experiments::attack(); - return; - } - - if(event.button == GLFW_MOUSE_BUTTON_RIGHT) { - experiments::interact(); - return; - } - } - } -} - -void experiments::init(void) -{ - globals::dispatcher.sink().connect<&on_glfw_mouse_button>(); -} - -void experiments::init_late(void) -{ - gui::hotbar::slots[0] = game_items::cobblestone; - gui::hotbar::slots[1] = game_items::stone; - gui::hotbar::slots[2] = game_items::dirt; - gui::hotbar::slots[3] = game_items::grass; - gui::hotbar::slots[4] = game_items::oak_leaves; - gui::hotbar::slots[5] = game_items::oak_planks; - gui::hotbar::slots[6] = game_items::oak_log; - gui::hotbar::slots[7] = game_items::glass; - gui::hotbar::slots[8] = game_items::slime; -} - -void experiments::shutdown(void) -{ -} - -void experiments::update(void) -{ -} - -void experiments::update_late(void) -{ -} - -void experiments::attack(void) -{ - globals::dimension->set_voxel(NULL_VOXEL_ID, world::player_target::coord); -} - -void experiments::interact(void) -{ - if(auto info = world::item_registry::find(gui::hotbar::slots[gui::hotbar::active_slot])) { - if(info->place_voxel != NULL_VOXEL_ID) { - globals::dimension->set_voxel(info->place_voxel, world::player_target::coord + world::player_target::normal); - } - } -} +#include "client/pch.hh" + +#include "client/experiments.hh" + +#include "shared/world/dimension.hh" +#include "shared/world/item_registry.hh" + +#include "shared/game_items.hh" +#include "shared/game_voxels.hh" + +#include "client/gui/chat.hh" +#include "client/gui/hotbar.hh" +#include "client/gui/status_lines.hh" + +#include "client/io/glfw.hh" + +#include "client/world/player_target.hh" + +#include "client/globals.hh" +#include "client/session.hh" + +static void on_glfw_mouse_button(const io::GlfwMouseButtonEvent& event) +{ + if(!globals::gui_screen && session::is_ingame()) { + if((event.action == GLFW_PRESS) && (world::player_target::voxel != NULL_VOXEL_ID)) { + if(event.button == GLFW_MOUSE_BUTTON_LEFT) { + experiments::attack(); + return; + } + + if(event.button == GLFW_MOUSE_BUTTON_RIGHT) { + experiments::interact(); + return; + } + } + } +} + +void experiments::init(void) +{ + globals::dispatcher.sink().connect<&on_glfw_mouse_button>(); +} + +void experiments::init_late(void) +{ + gui::hotbar::slots[0] = game_items::cobblestone; + gui::hotbar::slots[1] = game_items::stone; + gui::hotbar::slots[2] = game_items::dirt; + gui::hotbar::slots[3] = game_items::grass; + gui::hotbar::slots[4] = game_items::oak_leaves; + gui::hotbar::slots[5] = game_items::oak_planks; + gui::hotbar::slots[6] = game_items::oak_log; + gui::hotbar::slots[7] = game_items::glass; + gui::hotbar::slots[8] = game_items::slime; +} + +void experiments::shutdown(void) +{ +} + +void experiments::update(void) +{ +} + +void experiments::update_late(void) +{ +} + +void experiments::attack(void) +{ + globals::dimension->set_voxel(NULL_VOXEL_ID, world::player_target::coord); +} + +void experiments::interact(void) +{ + if(auto info = world::item_registry::find(gui::hotbar::slots[gui::hotbar::active_slot])) { + if(info->place_voxel != NULL_VOXEL_ID) { + globals::dimension->set_voxel(info->place_voxel, world::player_target::coord + world::player_target::normal); + } + } +} diff --git a/game/client/experiments.hh b/game/client/experiments.hh index ff2cbad..c1b0769 100644 --- a/game/client/experiments.hh +++ b/game/client/experiments.hh @@ -1,16 +1,16 @@ -#pragma once - -namespace experiments -{ -void init(void); -void init_late(void); -void shutdown(void); -void update(void); -void update_late(void); -} // namespace experiments - -namespace experiments -{ -void attack(void); -void interact(void); -} // namespace experiments +#pragma once + +namespace experiments +{ +void init(void); +void init_late(void); +void shutdown(void); +void update(void); +void update_late(void); +} // namespace experiments + +namespace experiments +{ +void attack(void); +void interact(void); +} // namespace experiments diff --git a/game/client/game.cc b/game/client/game.cc index 118ac66..a59aec3 100644 --- a/game/client/game.cc +++ b/game/client/game.cc @@ -1,693 +1,693 @@ -#include "client/pch.hh" - -#include "client/game.hh" - -#include "core/config/boolean.hh" -#include "core/config/number.hh" -#include "core/config/string.hh" - -#include "core/io/config_map.hh" - -#include "core/math/angles.hh" - -#include "core/resource/resource.hh" - -#include "core/utils/physfs.hh" - -#include "shared/entity/collision.hh" -#include "shared/entity/gravity.hh" -#include "shared/entity/head.hh" -#include "shared/entity/player.hh" -#include "shared/entity/stasis.hh" -#include "shared/entity/transform.hh" -#include "shared/entity/velocity.hh" - -#include "shared/game_items.hh" -#include "shared/game_voxels.hh" - -#include "shared/world/dimension.hh" -#include "shared/world/item_registry.hh" -#include "shared/world/ray_dda.hh" -#include "shared/world/voxel_registry.hh" - -#include "shared/coord.hh" -#include "shared/protocol.hh" - -#include "client/config/keybind.hh" - -#include "client/entity/camera.hh" -#include "client/entity/interpolation.hh" -#include "client/entity/listener.hh" -#include "client/entity/player_look.hh" -#include "client/entity/player_move.hh" -#include "client/entity/sound_emitter.hh" - -#include "client/gui/background.hh" -#include "client/gui/bother.hh" -#include "client/gui/chat.hh" -#include "client/gui/crosshair.hh" -#include "client/gui/direct_connection.hh" -#include "client/gui/gui_screen.hh" -#include "client/gui/hotbar.hh" -#include "client/gui/language.hh" -#include "client/gui/main_menu.hh" -#include "client/gui/message_box.hh" -#include "client/gui/metrics.hh" -#include "client/gui/play_menu.hh" -#include "client/gui/progress_bar.hh" -#include "client/gui/scoreboard.hh" -#include "client/gui/settings.hh" -#include "client/gui/splash.hh" -#include "client/gui/status_lines.hh" -#include "client/gui/window_title.hh" - -#include "client/io/gamepad.hh" -#include "client/io/glfw.hh" - -#include "client/resource/texture_gui.hh" - -#include "client/sound/sound.hh" - -#include "client/world/chunk_mesher.hh" -#include "client/world/chunk_renderer.hh" -#include "client/world/chunk_visibility.hh" -#include "client/world/outline.hh" -#include "client/world/player_target.hh" -#include "client/world/skybox.hh" -#include "client/world/voxel_anims.hh" -#include "client/world/voxel_atlas.hh" -#include "client/world/voxel_sounds.hh" - -#include "client/const.hh" -#include "client/experiments.hh" -#include "client/globals.hh" -#include "client/receive.hh" -#include "client/screenshot.hh" -#include "client/session.hh" -#include "client/toggles.hh" - -config::Boolean client_game::streamer_mode(false); -config::Boolean client_game::vertical_sync(true); -config::Boolean client_game::world_curvature(true); -config::Unsigned client_game::fog_mode(1U, 0U, 2U); -config::String client_game::username("player"); - -bool client_game::hide_hud = false; - -static config::KeyBind hide_hud_toggle(GLFW_KEY_F1); - -static ImFont* load_font(std::string_view path, float size, ImFontConfig& font_config, ImVector& ranges) -{ - bool font_load_success; - std::vector font; - - if(!utils::read_file(path, font)) { - spdlog::error("{}: utils::read_file failed", path); - std::terminate(); - } - - auto& io = ImGui::GetIO(); - auto font_ptr = io.Fonts->AddFontFromMemoryTTF(font.data(), font.size(), size, &font_config, ranges.Data); - - if(font_ptr == nullptr) { - spdlog::error("{}: AddFontFromMemoryTTF failed", path); - std::terminate(); - } - - return font_ptr; -} - -static void on_glfw_framebuffer_size(const io::GlfwFramebufferSizeEvent& event) -{ - if(globals::world_fbo) { - glDeleteRenderbuffers(1, &globals::world_fbo_depth); - glDeleteTextures(1, &globals::world_fbo_color); - glDeleteFramebuffers(1, &globals::world_fbo); - } - - glGenFramebuffers(1, &globals::world_fbo); - glGenTextures(1, &globals::world_fbo_color); - glGenRenderbuffers(1, &globals::world_fbo_depth); - - glBindTexture(GL_TEXTURE_2D, globals::world_fbo_color); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, event.size.x, event.size.y, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr); - - glBindRenderbuffer(GL_RENDERBUFFER, globals::world_fbo_depth); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, event.size.x, event.size.y); - - glBindFramebuffer(GL_FRAMEBUFFER, globals::world_fbo); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, globals::world_fbo_color, 0); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, globals::world_fbo_depth); - - if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - spdlog::critical("opengl: world framebuffer is incomplete"); - glDeleteRenderbuffers(1, &globals::world_fbo_depth); - glDeleteTextures(1, &globals::world_fbo_color); - glDeleteFramebuffers(1, &globals::world_fbo); - std::terminate(); - } -} - -static void on_glfw_key(const io::GlfwKeyEvent& event) -{ - if(!globals::gui_keybind_ptr && hide_hud_toggle.equals(event.key) && (event.action == GLFW_PRESS)) { - client_game::hide_hud = !client_game::hide_hud; - } -} - -void client_game::init(void) -{ - auto& io = ImGui::GetIO(); - io.ConfigFlags &= ~ImGuiConfigFlags_NavEnableGamepad; - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; - io.IniFilename = nullptr; - io.Fonts->Clear(); - - ImFontConfig font_config; - font_config.FontDataOwnedByAtlas = false; - - ImFontGlyphRangesBuilder builder; - builder.AddRanges(io.Fonts->GetGlyphRangesDefault()); - builder.AddRanges(io.Fonts->GetGlyphRangesCyrillic()); - - ImVector ranges; - builder.BuildRanges(&ranges); - - globals::font_unscii16 = load_font("fonts/unscii-16.ttf", 16.0f, font_config, ranges); - globals::font_unscii8 = load_font("fonts/unscii-8.ttf", 8.0f, font_config, ranges); - - gui::client_splash::init(); - gui::client_splash::render(); - - globals::client_config.add_value("game.streamer_mode", client_game::streamer_mode); - globals::client_config.add_value("game.vertical_sync", client_game::vertical_sync); - globals::client_config.add_value("game.world_curvature", client_game::world_curvature); - globals::client_config.add_value("game.fog_mode", client_game::fog_mode); - globals::client_config.add_value("game.username", client_game::username); - globals::client_config.add_value("game.key.toggle_hide_hud", hide_hud_toggle); - - settings::init(); - - settings::add_checkbox(0, client_game::streamer_mode, settings_location::VIDEO_GUI, "game.streamer_mode", true); - settings::add_checkbox(5, client_game::vertical_sync, settings_location::VIDEO, "game.vertical_sync", false); - settings::add_checkbox(4, client_game::world_curvature, settings_location::VIDEO, "game.world_curvature", true); - settings::add_stepper(3, client_game::fog_mode, settings_location::VIDEO, "game.fog_mode", false); - settings::add_input(1, client_game::username, settings_location::GENERAL, "game.username", true, false); - settings::add_keybind(4, hide_hud_toggle, settings_location::KEYBOARD_MISC, "game.key.toggle_hide_hud"); - - globals::client_host = enet_host_create(nullptr, 1, 1, 0, 0); - - if(!globals::client_host) { - spdlog::critical("game: unable to setup an ENet host"); - std::terminate(); - } - - gui::language::init(); - - session::init(); - - entity::player_look::init(); - entity::player_move::init(); - world::player_target::init(); - - io::gamepad::init(); - - entity::camera::init(); - - world::voxel_anims::init(); - - world::outline::init(); - world::chunk_mesher::init(); - world::chunk_renderer::init(); - - globals::world_fbo = 0; - globals::world_fbo_color = 0; - globals::world_fbo_depth = 0; - - world::voxel_sounds::init(); - - world::skybox::init(); - - ImGuiStyle& style = ImGui::GetStyle(); - - // Black buttons on a dark background - // may be harder to read than the text on them - style.FrameBorderSize = 1.0; - style.TabBorderSize = 1.0; - - // Rounding on elements looks cool but I am - // aiming for a more or less blocky and - // visually simple HiDPI-friendly UI style - style.TabRounding = 0.0f; - style.GrabRounding = 0.0f; - style.ChildRounding = 0.0f; - style.FrameRounding = 0.0f; - style.PopupRounding = 0.0f; - style.WindowRounding = 0.0f; - style.ScrollbarRounding = 0.0f; - - style.Colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); - style.Colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); - style.Colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - style.Colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); - style.Colors[ImGuiCol_Border] = ImVec4(0.79f, 0.79f, 0.79f, 0.50f); - style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - style.Colors[ImGuiCol_FrameBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.54f); - style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.36f, 0.36f, 0.36f, 0.40f); - style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.63f, 0.63f, 0.63f, 0.67f); - style.Colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); - style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); - style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); - style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); - style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); - style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.00f, 0.00f, 0.00f, 0.75f); - style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); - style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); - style.Colors[ImGuiCol_CheckMark] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.81f, 0.81f, 0.81f, 0.75f); - style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); - style.Colors[ImGuiCol_Button] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); - style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); - style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); - style.Colors[ImGuiCol_Header] = ImVec4(0.00f, 0.00f, 0.00f, 0.75f); - style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); - style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); - style.Colors[ImGuiCol_Separator] = ImVec4(0.49f, 0.49f, 0.49f, 0.50f); - style.Colors[ImGuiCol_SeparatorHovered] = ImVec4(0.56f, 0.56f, 0.56f, 0.78f); - style.Colors[ImGuiCol_SeparatorActive] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); - style.Colors[ImGuiCol_ResizeGrip] = ImVec4(0.34f, 0.34f, 0.34f, 0.20f); - style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.57f, 0.57f, 0.57f, 0.67f); - style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.95f); - style.Colors[ImGuiCol_Tab] = ImVec4(0.00f, 0.00f, 0.00f, 0.75f); - style.Colors[ImGuiCol_TabHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); - style.Colors[ImGuiCol_TabActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); - style.Colors[ImGuiCol_TabUnfocused] = ImVec4(0.13f, 0.13f, 0.13f, 0.97f); - style.Colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.44f, 0.44f, 0.44f, 1.00f); - style.Colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); - style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.69f, 0.00f, 0.00f, 1.00f); - style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.00f, 1.00f, 0.20f, 1.00f); - style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); - style.Colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); - style.Colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); - style.Colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); - style.Colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - style.Colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); - style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.61f, 0.61f, 0.61f, 0.35f); - style.Colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 1.00f); - style.Colors[ImGuiCol_NavHighlight] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); - style.Colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); - style.Colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); - style.Colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); - - // Making my own Game UI for Source Engine - // taught me one important thing: dimensions - // of UI elements must be calculated at semi-runtime - // so there's simply no point for an INI file. - io.IniFilename = nullptr; - - toggles::init(); - - gui::background::init(); - - gui::scoreboard::init(); - - gui::client_chat::init(); - - gui::bother::init(); - - gui::main_menu::init(); - gui::play_menu::init(); - gui::progress_bar::init(); - gui::message_box::init(); - gui::direct_connection::init(); - - gui::crosshair::init(); - gui::hotbar::init(); - gui::metrics::init(); - gui::status_lines::init(); - - screenshot::init(); - - globals::gui_keybind_ptr = nullptr; - globals::gui_scale = 0U; - globals::gui_screen = GUI_MAIN_MENU; - - sound::init_config(); - - if(globals::sound_ctx) { - sound::init(); - } - - client_receive::init(); - - experiments::init(); - - globals::dispatcher.sink().connect<&on_glfw_framebuffer_size>(); - globals::dispatcher.sink().connect<&on_glfw_key>(); -} - -void client_game::init_late(void) -{ - toggles::init_late(); - - if(globals::sound_ctx) { - sound::init_late(); - } - - gui::language::init_late(); - - settings::init_late(); - - gui::client_chat::init_late(); - - gui::status_lines::init_late(); - - game_voxels::populate(); - game_items::populate(); - - std::size_t max_texture_count = 0; - - // Figure out the total texture count - // NOTE: this is very debug, early and a quite - // conservative limit choice; there must be a better - // way to make this limit way smaller than it currently is - for(const std::shared_ptr& info : world::voxel_registry::voxels) { - for(const world::VoxelTexture& vtex : info->textures) { - max_texture_count += vtex.paths.size(); - } - } - - // UNDONE: asset packs for non-16x16 stuff - world::voxel_atlas::create(16, 16, max_texture_count); - - for(std::shared_ptr& info : world::voxel_registry::voxels) { - for(world::VoxelTexture& vtex : info->textures) { - if(auto strip = world::voxel_atlas::find_or_load(vtex.paths)) { - vtex.cached_offset = strip->offset; - vtex.cached_plane = strip->plane; - continue; - } - - spdlog::critical("client_gl: {}: failed to load atlas strips", info->name); - std::terminate(); - } - } - - world::voxel_atlas::generate_mipmaps(); - - for(std::shared_ptr& info : world::item_registry::items) { - info->cached_texture = resource::load(info->texture.c_str(), TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); - } - - experiments::init_late(); - - gui::client_splash::init_late(); - - gui::window_title::update(); -} - -void client_game::shutdown(void) -{ - world::voxel_sounds::shutdown(); - - experiments::shutdown(); - - session::shutdown(); - - if(globals::sound_ctx) { - sound::shutdown(); - } - - gui::hotbar::shutdown(); - gui::main_menu::shutdown(); - gui::play_menu::shutdown(); - - gui::bother::shutdown(); - - gui::client_chat::shutdown(); - - gui::background::shutdown(); - - gui::crosshair::shutdown(); - - delete globals::dimension; - globals::player = entt::null; - globals::dimension = nullptr; - - world::item_registry::purge(); - world::voxel_registry::purge(); - - world::voxel_atlas::destroy(); - - glDeleteRenderbuffers(1, &globals::world_fbo_depth); - glDeleteTextures(1, &globals::world_fbo_color); - glDeleteFramebuffers(1, &globals::world_fbo); - - world::outline::shutdown(); - world::chunk_renderer::shutdown(); - world::chunk_mesher::shutdown(); - - enet_host_destroy(globals::client_host); -} - -void client_game::fixed_update(void) -{ - entity::player_move::fixed_update(); - - // Only update world simulation gamesystems - // if the player can actually observe all the - // changes these gamesystems cause visually - if(session::is_ingame()) { - entity::Collision::fixed_update(globals::dimension); - entity::Velocity::fixed_update(globals::dimension); - entity::Transform::fixed_update(globals::dimension); - entity::Gravity::fixed_update(globals::dimension); - entity::Stasis::fixed_update(globals::dimension); - } -} - -void client_game::fixed_update_late(void) -{ - if(session::is_ingame()) { - const auto& head = globals::dimension->entities.get(globals::player); - const auto& transform = globals::dimension->entities.get(globals::player); - const auto& velocity = globals::dimension->entities.get(globals::player); - - protocol::EntityHead head_packet; - head_packet.entity = entt::null; // ignored by server - head_packet.angles = head.angles; - - protocol::EntityTransform transform_packet; - transform_packet.entity = entt::null; // ignored by server - transform_packet.angles = transform.angles; - transform_packet.chunk = transform.chunk; - transform_packet.local = transform.local; - - protocol::EntityVelocity velocity_packet; - velocity_packet.entity = entt::null; // ignored by server - velocity_packet.value = velocity.value; - - protocol::send(session::peer, protocol::encode(head_packet)); - protocol::send(session::peer, protocol::encode(transform_packet)); - protocol::send(session::peer, protocol::encode(velocity_packet)); - } -} - -void client_game::update(void) -{ - if(session::is_ingame()) { - if(toggles::get(TOGGLE_PM_FLIGHT)) { - globals::dimension->entities.remove(globals::player); - } - else { - globals::dimension->entities.emplace_or_replace(globals::player); - } - } - - if(globals::sound_ctx) { - sound::update(); - - entity::listener::update(); - - entity::SoundEmitter::update(); - } - - entity::interpolation::update(); - - world::player_target::update(); - - entity::camera::update(); - - world::voxel_anims::update(); - - world::chunk_mesher::update(); - - gui::client_chat::update(); - - experiments::update(); - - constexpr auto half_base_width = 0.5f * static_cast(BASE_WIDTH); - constexpr auto half_base_height = 0.5f * static_cast(BASE_HEIGHT); - - auto twice_scale_x = static_cast(globals::width) / half_base_width; - auto twice_scale_y = static_cast(globals::height) / half_base_height; - - auto scale_x = math::max(1.0f, 0.5f * glm::floor(twice_scale_x)); - auto scale_y = math::max(1.0f, 0.5f * glm::floor(twice_scale_y)); - auto scale_min = math::ceil(math::min(scale_x, scale_y)); - auto scale_int = math::max(1U, (scale_min / 2U) * 2U); - - auto& io = ImGui::GetIO(); - io.FontGlobalScale = scale_int; - globals::gui_scale = scale_int; -} - -void client_game::update_late(void) -{ - ENetEvent enet_event; - - while(0 < enet_host_service(globals::client_host, &enet_event, 0)) { - switch(enet_event.type) { - case ENET_EVENT_TYPE_CONNECT: - session::send_login_request(); - break; - case ENET_EVENT_TYPE_DISCONNECT: - session::invalidate(); - break; - case ENET_EVENT_TYPE_RECEIVE: - protocol::decode(globals::dispatcher, enet_event.packet, enet_event.peer); - enet_packet_destroy(enet_event.packet); - break; - } - } - - entity::player_look::update_late(); - entity::player_move::update_late(); - - gui::play_menu::update_late(); - - gui::bother::update_late(); - - experiments::update_late(); - - io::gamepad::update_late(); - - world::chunk_visibility::update_late(); - - if(client_game::vertical_sync.get_value()) { - glfwSwapInterval(1); - } - else { - glfwSwapInterval(0); - } -} - -void client_game::render(void) -{ - glViewport(0, 0, globals::width, globals::height); - glBindFramebuffer(GL_FRAMEBUFFER, globals::world_fbo); - glClearColor(world::skybox::fog_color.r, world::skybox::fog_color.g, world::skybox::fog_color.b, 1.000f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - if(globals::dimension) { - world::chunk_renderer::render(); - } - - glEnable(GL_DEPTH_TEST); - - world::player_target::render(); - - if(globals::dimension) { - auto group = globals::dimension->entities.group( - entt::get); - - world::outline::prepare(); - - for(const auto [entity, collision, head, transform] : group.each()) { - if(entity == globals::player) { - // Don't render ourselves - continue; - } - - glm::fvec3 forward; - math::vectors(transform.angles + head.angles, forward); - forward *= 2.0f; - - glm::fvec3 hull_size = collision.aabb.max - collision.aabb.min; - glm::fvec3 hull_fpos = transform.local + collision.aabb.min; - glm::fvec3 look = transform.local + head.offset; - - world::outline::cube(transform.chunk, hull_fpos, hull_size, 1.0f, glm::fvec4(1.0f, 0.0f, 0.0f, 1.0f)); - world::outline::line(transform.chunk, look, forward, 1.0f, glm::fvec4(0.9f, 0.9f, 0.9f, 1.0f)); - } - } - - glEnable(GL_DEPTH_TEST); - - glViewport(0, 0, globals::width, globals::height); - glClearColor(0.000f, 0.000f, 0.000f, 1.000f); - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glClear(GL_COLOR_BUFFER_BIT); - - glBindFramebuffer(GL_READ_FRAMEBUFFER, globals::world_fbo); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - glBlitFramebuffer(0, 0, globals::width, globals::height, 0, 0, globals::width, globals::height, GL_COLOR_BUFFER_BIT, GL_NEAREST); -} - -void client_game::layout(void) -{ - if(!session::is_ingame()) { - gui::background::layout(); - } - - if(!globals::gui_screen || (globals::gui_screen == GUI_CHAT)) { - if(toggles::get(TOGGLE_METRICS_UI) && !client_game::hide_hud) { - // This contains Minecraft-esque debug information - // about the hardware, world state and other - // things that might be uesful - gui::metrics::layout(); - } - } - - if(session::is_ingame()) { - gui::client_chat::layout(); - gui::scoreboard::layout(); - - if(!globals::gui_screen && !client_game::hide_hud) { - gui::hotbar::layout(); - gui::status_lines::layout(); - gui::crosshair::layout(); - } - } - - if(globals::gui_screen) { - if(session::is_ingame() && (globals::gui_screen != GUI_CHAT)) { - const float width_f = static_cast(globals::width); - const float height_f = static_cast(globals::height); - const ImU32 darken = ImGui::GetColorU32(ImVec4(0.00f, 0.00f, 0.00f, 0.75f)); - ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(), ImVec2(width_f, height_f), darken); - } - - switch(globals::gui_screen) { - case GUI_MAIN_MENU: - gui::main_menu::layout(); - break; - case GUI_PLAY_MENU: - gui::play_menu::layout(); - break; - case GUI_SETTINGS: - settings::layout(); - break; - case GUI_PROGRESS_BAR: - gui::progress_bar::layout(); - break; - case GUI_MESSAGE_BOX: - gui::message_box::layout(); - break; - case GUI_DIRECT_CONNECTION: - gui::direct_connection::layout(); - break; - } - } -} +#include "client/pch.hh" + +#include "client/game.hh" + +#include "core/config/boolean.hh" +#include "core/config/number.hh" +#include "core/config/string.hh" + +#include "core/io/config_map.hh" + +#include "core/math/angles.hh" + +#include "core/resource/resource.hh" + +#include "core/utils/physfs.hh" + +#include "shared/entity/collision.hh" +#include "shared/entity/gravity.hh" +#include "shared/entity/head.hh" +#include "shared/entity/player.hh" +#include "shared/entity/stasis.hh" +#include "shared/entity/transform.hh" +#include "shared/entity/velocity.hh" + +#include "shared/game_items.hh" +#include "shared/game_voxels.hh" + +#include "shared/world/dimension.hh" +#include "shared/world/item_registry.hh" +#include "shared/world/ray_dda.hh" +#include "shared/world/voxel_registry.hh" + +#include "shared/coord.hh" +#include "shared/protocol.hh" + +#include "client/config/keybind.hh" + +#include "client/entity/camera.hh" +#include "client/entity/interpolation.hh" +#include "client/entity/listener.hh" +#include "client/entity/player_look.hh" +#include "client/entity/player_move.hh" +#include "client/entity/sound_emitter.hh" + +#include "client/gui/background.hh" +#include "client/gui/bother.hh" +#include "client/gui/chat.hh" +#include "client/gui/crosshair.hh" +#include "client/gui/direct_connection.hh" +#include "client/gui/gui_screen.hh" +#include "client/gui/hotbar.hh" +#include "client/gui/language.hh" +#include "client/gui/main_menu.hh" +#include "client/gui/message_box.hh" +#include "client/gui/metrics.hh" +#include "client/gui/play_menu.hh" +#include "client/gui/progress_bar.hh" +#include "client/gui/scoreboard.hh" +#include "client/gui/settings.hh" +#include "client/gui/splash.hh" +#include "client/gui/status_lines.hh" +#include "client/gui/window_title.hh" + +#include "client/io/gamepad.hh" +#include "client/io/glfw.hh" + +#include "client/resource/texture_gui.hh" + +#include "client/sound/sound.hh" + +#include "client/world/chunk_mesher.hh" +#include "client/world/chunk_renderer.hh" +#include "client/world/chunk_visibility.hh" +#include "client/world/outline.hh" +#include "client/world/player_target.hh" +#include "client/world/skybox.hh" +#include "client/world/voxel_anims.hh" +#include "client/world/voxel_atlas.hh" +#include "client/world/voxel_sounds.hh" + +#include "client/const.hh" +#include "client/experiments.hh" +#include "client/globals.hh" +#include "client/receive.hh" +#include "client/screenshot.hh" +#include "client/session.hh" +#include "client/toggles.hh" + +config::Boolean client_game::streamer_mode(false); +config::Boolean client_game::vertical_sync(true); +config::Boolean client_game::world_curvature(true); +config::Unsigned client_game::fog_mode(1U, 0U, 2U); +config::String client_game::username("player"); + +bool client_game::hide_hud = false; + +static config::KeyBind hide_hud_toggle(GLFW_KEY_F1); + +static ImFont* load_font(std::string_view path, float size, ImFontConfig& font_config, ImVector& ranges) +{ + bool font_load_success; + std::vector font; + + if(!utils::read_file(path, font)) { + spdlog::error("{}: utils::read_file failed", path); + std::terminate(); + } + + auto& io = ImGui::GetIO(); + auto font_ptr = io.Fonts->AddFontFromMemoryTTF(font.data(), font.size(), size, &font_config, ranges.Data); + + if(font_ptr == nullptr) { + spdlog::error("{}: AddFontFromMemoryTTF failed", path); + std::terminate(); + } + + return font_ptr; +} + +static void on_glfw_framebuffer_size(const io::GlfwFramebufferSizeEvent& event) +{ + if(globals::world_fbo) { + glDeleteRenderbuffers(1, &globals::world_fbo_depth); + glDeleteTextures(1, &globals::world_fbo_color); + glDeleteFramebuffers(1, &globals::world_fbo); + } + + glGenFramebuffers(1, &globals::world_fbo); + glGenTextures(1, &globals::world_fbo_color); + glGenRenderbuffers(1, &globals::world_fbo_depth); + + glBindTexture(GL_TEXTURE_2D, globals::world_fbo_color); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, event.size.x, event.size.y, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr); + + glBindRenderbuffer(GL_RENDERBUFFER, globals::world_fbo_depth); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, event.size.x, event.size.y); + + glBindFramebuffer(GL_FRAMEBUFFER, globals::world_fbo); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, globals::world_fbo_color, 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, globals::world_fbo_depth); + + if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + spdlog::critical("opengl: world framebuffer is incomplete"); + glDeleteRenderbuffers(1, &globals::world_fbo_depth); + glDeleteTextures(1, &globals::world_fbo_color); + glDeleteFramebuffers(1, &globals::world_fbo); + std::terminate(); + } +} + +static void on_glfw_key(const io::GlfwKeyEvent& event) +{ + if(!globals::gui_keybind_ptr && hide_hud_toggle.equals(event.key) && (event.action == GLFW_PRESS)) { + client_game::hide_hud = !client_game::hide_hud; + } +} + +void client_game::init(void) +{ + auto& io = ImGui::GetIO(); + io.ConfigFlags &= ~ImGuiConfigFlags_NavEnableGamepad; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; + io.IniFilename = nullptr; + io.Fonts->Clear(); + + ImFontConfig font_config; + font_config.FontDataOwnedByAtlas = false; + + ImFontGlyphRangesBuilder builder; + builder.AddRanges(io.Fonts->GetGlyphRangesDefault()); + builder.AddRanges(io.Fonts->GetGlyphRangesCyrillic()); + + ImVector ranges; + builder.BuildRanges(&ranges); + + globals::font_unscii16 = load_font("fonts/unscii-16.ttf", 16.0f, font_config, ranges); + globals::font_unscii8 = load_font("fonts/unscii-8.ttf", 8.0f, font_config, ranges); + + gui::client_splash::init(); + gui::client_splash::render(); + + globals::client_config.add_value("game.streamer_mode", client_game::streamer_mode); + globals::client_config.add_value("game.vertical_sync", client_game::vertical_sync); + globals::client_config.add_value("game.world_curvature", client_game::world_curvature); + globals::client_config.add_value("game.fog_mode", client_game::fog_mode); + globals::client_config.add_value("game.username", client_game::username); + globals::client_config.add_value("game.key.toggle_hide_hud", hide_hud_toggle); + + settings::init(); + + settings::add_checkbox(0, client_game::streamer_mode, settings_location::VIDEO_GUI, "game.streamer_mode", true); + settings::add_checkbox(5, client_game::vertical_sync, settings_location::VIDEO, "game.vertical_sync", false); + settings::add_checkbox(4, client_game::world_curvature, settings_location::VIDEO, "game.world_curvature", true); + settings::add_stepper(3, client_game::fog_mode, settings_location::VIDEO, "game.fog_mode", false); + settings::add_input(1, client_game::username, settings_location::GENERAL, "game.username", true, false); + settings::add_keybind(4, hide_hud_toggle, settings_location::KEYBOARD_MISC, "game.key.toggle_hide_hud"); + + globals::client_host = enet_host_create(nullptr, 1, 1, 0, 0); + + if(!globals::client_host) { + spdlog::critical("game: unable to setup an ENet host"); + std::terminate(); + } + + gui::language::init(); + + session::init(); + + entity::player_look::init(); + entity::player_move::init(); + world::player_target::init(); + + io::gamepad::init(); + + entity::camera::init(); + + world::voxel_anims::init(); + + world::outline::init(); + world::chunk_mesher::init(); + world::chunk_renderer::init(); + + globals::world_fbo = 0; + globals::world_fbo_color = 0; + globals::world_fbo_depth = 0; + + world::voxel_sounds::init(); + + world::skybox::init(); + + ImGuiStyle& style = ImGui::GetStyle(); + + // Black buttons on a dark background + // may be harder to read than the text on them + style.FrameBorderSize = 1.0; + style.TabBorderSize = 1.0; + + // Rounding on elements looks cool but I am + // aiming for a more or less blocky and + // visually simple HiDPI-friendly UI style + style.TabRounding = 0.0f; + style.GrabRounding = 0.0f; + style.ChildRounding = 0.0f; + style.FrameRounding = 0.0f; + style.PopupRounding = 0.0f; + style.WindowRounding = 0.0f; + style.ScrollbarRounding = 0.0f; + + style.Colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + style.Colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); + style.Colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + style.Colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + style.Colors[ImGuiCol_Border] = ImVec4(0.79f, 0.79f, 0.79f, 0.50f); + style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + style.Colors[ImGuiCol_FrameBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.54f); + style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.36f, 0.36f, 0.36f, 0.40f); + style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.63f, 0.63f, 0.63f, 0.67f); + style.Colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); + style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); + style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); + style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); + style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.00f, 0.00f, 0.00f, 0.75f); + style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); + style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + style.Colors[ImGuiCol_CheckMark] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + style.Colors[ImGuiCol_SliderGrab] = ImVec4(0.81f, 0.81f, 0.81f, 0.75f); + style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + style.Colors[ImGuiCol_Button] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); + style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + style.Colors[ImGuiCol_Header] = ImVec4(0.00f, 0.00f, 0.00f, 0.75f); + style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); + style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + style.Colors[ImGuiCol_Separator] = ImVec4(0.49f, 0.49f, 0.49f, 0.50f); + style.Colors[ImGuiCol_SeparatorHovered] = ImVec4(0.56f, 0.56f, 0.56f, 0.78f); + style.Colors[ImGuiCol_SeparatorActive] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + style.Colors[ImGuiCol_ResizeGrip] = ImVec4(0.34f, 0.34f, 0.34f, 0.20f); + style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.57f, 0.57f, 0.57f, 0.67f); + style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.95f); + style.Colors[ImGuiCol_Tab] = ImVec4(0.00f, 0.00f, 0.00f, 0.75f); + style.Colors[ImGuiCol_TabHovered] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); + style.Colors[ImGuiCol_TabActive] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + style.Colors[ImGuiCol_TabUnfocused] = ImVec4(0.13f, 0.13f, 0.13f, 0.97f); + style.Colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.44f, 0.44f, 0.44f, 1.00f); + style.Colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); + style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.69f, 0.00f, 0.00f, 1.00f); + style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.00f, 1.00f, 0.20f, 1.00f); + style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + style.Colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); + style.Colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); + style.Colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); + style.Colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + style.Colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); + style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.61f, 0.61f, 0.61f, 0.35f); + style.Colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 1.00f); + style.Colors[ImGuiCol_NavHighlight] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + style.Colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + style.Colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + style.Colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); + + // Making my own Game UI for Source Engine + // taught me one important thing: dimensions + // of UI elements must be calculated at semi-runtime + // so there's simply no point for an INI file. + io.IniFilename = nullptr; + + toggles::init(); + + gui::background::init(); + + gui::scoreboard::init(); + + gui::client_chat::init(); + + gui::bother::init(); + + gui::main_menu::init(); + gui::play_menu::init(); + gui::progress_bar::init(); + gui::message_box::init(); + gui::direct_connection::init(); + + gui::crosshair::init(); + gui::hotbar::init(); + gui::metrics::init(); + gui::status_lines::init(); + + screenshot::init(); + + globals::gui_keybind_ptr = nullptr; + globals::gui_scale = 0U; + globals::gui_screen = GUI_MAIN_MENU; + + sound::init_config(); + + if(globals::sound_ctx) { + sound::init(); + } + + client_receive::init(); + + experiments::init(); + + globals::dispatcher.sink().connect<&on_glfw_framebuffer_size>(); + globals::dispatcher.sink().connect<&on_glfw_key>(); +} + +void client_game::init_late(void) +{ + toggles::init_late(); + + if(globals::sound_ctx) { + sound::init_late(); + } + + gui::language::init_late(); + + settings::init_late(); + + gui::client_chat::init_late(); + + gui::status_lines::init_late(); + + game_voxels::populate(); + game_items::populate(); + + std::size_t max_texture_count = 0; + + // Figure out the total texture count + // NOTE: this is very debug, early and a quite + // conservative limit choice; there must be a better + // way to make this limit way smaller than it currently is + for(const std::shared_ptr& info : world::voxel_registry::voxels) { + for(const world::VoxelTexture& vtex : info->textures) { + max_texture_count += vtex.paths.size(); + } + } + + // UNDONE: asset packs for non-16x16 stuff + world::voxel_atlas::create(16, 16, max_texture_count); + + for(std::shared_ptr& info : world::voxel_registry::voxels) { + for(world::VoxelTexture& vtex : info->textures) { + if(auto strip = world::voxel_atlas::find_or_load(vtex.paths)) { + vtex.cached_offset = strip->offset; + vtex.cached_plane = strip->plane; + continue; + } + + spdlog::critical("client_gl: {}: failed to load atlas strips", info->name); + std::terminate(); + } + } + + world::voxel_atlas::generate_mipmaps(); + + for(std::shared_ptr& info : world::item_registry::items) { + info->cached_texture = resource::load(info->texture.c_str(), TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); + } + + experiments::init_late(); + + gui::client_splash::init_late(); + + gui::window_title::update(); +} + +void client_game::shutdown(void) +{ + world::voxel_sounds::shutdown(); + + experiments::shutdown(); + + session::shutdown(); + + if(globals::sound_ctx) { + sound::shutdown(); + } + + gui::hotbar::shutdown(); + gui::main_menu::shutdown(); + gui::play_menu::shutdown(); + + gui::bother::shutdown(); + + gui::client_chat::shutdown(); + + gui::background::shutdown(); + + gui::crosshair::shutdown(); + + delete globals::dimension; + globals::player = entt::null; + globals::dimension = nullptr; + + world::item_registry::purge(); + world::voxel_registry::purge(); + + world::voxel_atlas::destroy(); + + glDeleteRenderbuffers(1, &globals::world_fbo_depth); + glDeleteTextures(1, &globals::world_fbo_color); + glDeleteFramebuffers(1, &globals::world_fbo); + + world::outline::shutdown(); + world::chunk_renderer::shutdown(); + world::chunk_mesher::shutdown(); + + enet_host_destroy(globals::client_host); +} + +void client_game::fixed_update(void) +{ + entity::player_move::fixed_update(); + + // Only update world simulation gamesystems + // if the player can actually observe all the + // changes these gamesystems cause visually + if(session::is_ingame()) { + entity::Collision::fixed_update(globals::dimension); + entity::Velocity::fixed_update(globals::dimension); + entity::Transform::fixed_update(globals::dimension); + entity::Gravity::fixed_update(globals::dimension); + entity::Stasis::fixed_update(globals::dimension); + } +} + +void client_game::fixed_update_late(void) +{ + if(session::is_ingame()) { + const auto& head = globals::dimension->entities.get(globals::player); + const auto& transform = globals::dimension->entities.get(globals::player); + const auto& velocity = globals::dimension->entities.get(globals::player); + + protocol::EntityHead head_packet; + head_packet.entity = entt::null; // ignored by server + head_packet.angles = head.angles; + + protocol::EntityTransform transform_packet; + transform_packet.entity = entt::null; // ignored by server + transform_packet.angles = transform.angles; + transform_packet.chunk = transform.chunk; + transform_packet.local = transform.local; + + protocol::EntityVelocity velocity_packet; + velocity_packet.entity = entt::null; // ignored by server + velocity_packet.value = velocity.value; + + protocol::send(session::peer, protocol::encode(head_packet)); + protocol::send(session::peer, protocol::encode(transform_packet)); + protocol::send(session::peer, protocol::encode(velocity_packet)); + } +} + +void client_game::update(void) +{ + if(session::is_ingame()) { + if(toggles::get(TOGGLE_PM_FLIGHT)) { + globals::dimension->entities.remove(globals::player); + } + else { + globals::dimension->entities.emplace_or_replace(globals::player); + } + } + + if(globals::sound_ctx) { + sound::update(); + + entity::listener::update(); + + entity::SoundEmitter::update(); + } + + entity::interpolation::update(); + + world::player_target::update(); + + entity::camera::update(); + + world::voxel_anims::update(); + + world::chunk_mesher::update(); + + gui::client_chat::update(); + + experiments::update(); + + constexpr auto half_base_width = 0.5f * static_cast(BASE_WIDTH); + constexpr auto half_base_height = 0.5f * static_cast(BASE_HEIGHT); + + auto twice_scale_x = static_cast(globals::width) / half_base_width; + auto twice_scale_y = static_cast(globals::height) / half_base_height; + + auto scale_x = math::max(1.0f, 0.5f * glm::floor(twice_scale_x)); + auto scale_y = math::max(1.0f, 0.5f * glm::floor(twice_scale_y)); + auto scale_min = math::ceil(math::min(scale_x, scale_y)); + auto scale_int = math::max(1U, (scale_min / 2U) * 2U); + + auto& io = ImGui::GetIO(); + io.FontGlobalScale = scale_int; + globals::gui_scale = scale_int; +} + +void client_game::update_late(void) +{ + ENetEvent enet_event; + + while(0 < enet_host_service(globals::client_host, &enet_event, 0)) { + switch(enet_event.type) { + case ENET_EVENT_TYPE_CONNECT: + session::send_login_request(); + break; + case ENET_EVENT_TYPE_DISCONNECT: + session::invalidate(); + break; + case ENET_EVENT_TYPE_RECEIVE: + protocol::decode(globals::dispatcher, enet_event.packet, enet_event.peer); + enet_packet_destroy(enet_event.packet); + break; + } + } + + entity::player_look::update_late(); + entity::player_move::update_late(); + + gui::play_menu::update_late(); + + gui::bother::update_late(); + + experiments::update_late(); + + io::gamepad::update_late(); + + world::chunk_visibility::update_late(); + + if(client_game::vertical_sync.get_value()) { + glfwSwapInterval(1); + } + else { + glfwSwapInterval(0); + } +} + +void client_game::render(void) +{ + glViewport(0, 0, globals::width, globals::height); + glBindFramebuffer(GL_FRAMEBUFFER, globals::world_fbo); + glClearColor(world::skybox::fog_color.r, world::skybox::fog_color.g, world::skybox::fog_color.b, 1.000f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + if(globals::dimension) { + world::chunk_renderer::render(); + } + + glEnable(GL_DEPTH_TEST); + + world::player_target::render(); + + if(globals::dimension) { + auto group = globals::dimension->entities.group( + entt::get); + + world::outline::prepare(); + + for(const auto [entity, collision, head, transform] : group.each()) { + if(entity == globals::player) { + // Don't render ourselves + continue; + } + + glm::fvec3 forward; + math::vectors(transform.angles + head.angles, forward); + forward *= 2.0f; + + glm::fvec3 hull_size = collision.aabb.max - collision.aabb.min; + glm::fvec3 hull_fpos = transform.local + collision.aabb.min; + glm::fvec3 look = transform.local + head.offset; + + world::outline::cube(transform.chunk, hull_fpos, hull_size, 1.0f, glm::fvec4(1.0f, 0.0f, 0.0f, 1.0f)); + world::outline::line(transform.chunk, look, forward, 1.0f, glm::fvec4(0.9f, 0.9f, 0.9f, 1.0f)); + } + } + + glEnable(GL_DEPTH_TEST); + + glViewport(0, 0, globals::width, globals::height); + glClearColor(0.000f, 0.000f, 0.000f, 1.000f); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glClear(GL_COLOR_BUFFER_BIT); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, globals::world_fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + glBlitFramebuffer(0, 0, globals::width, globals::height, 0, 0, globals::width, globals::height, GL_COLOR_BUFFER_BIT, GL_NEAREST); +} + +void client_game::layout(void) +{ + if(!session::is_ingame()) { + gui::background::layout(); + } + + if(!globals::gui_screen || (globals::gui_screen == GUI_CHAT)) { + if(toggles::get(TOGGLE_METRICS_UI) && !client_game::hide_hud) { + // This contains Minecraft-esque debug information + // about the hardware, world state and other + // things that might be uesful + gui::metrics::layout(); + } + } + + if(session::is_ingame()) { + gui::client_chat::layout(); + gui::scoreboard::layout(); + + if(!globals::gui_screen && !client_game::hide_hud) { + gui::hotbar::layout(); + gui::status_lines::layout(); + gui::crosshair::layout(); + } + } + + if(globals::gui_screen) { + if(session::is_ingame() && (globals::gui_screen != GUI_CHAT)) { + const float width_f = static_cast(globals::width); + const float height_f = static_cast(globals::height); + const ImU32 darken = ImGui::GetColorU32(ImVec4(0.00f, 0.00f, 0.00f, 0.75f)); + ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(), ImVec2(width_f, height_f), darken); + } + + switch(globals::gui_screen) { + case GUI_MAIN_MENU: + gui::main_menu::layout(); + break; + case GUI_PLAY_MENU: + gui::play_menu::layout(); + break; + case GUI_SETTINGS: + settings::layout(); + break; + case GUI_PROGRESS_BAR: + gui::progress_bar::layout(); + break; + case GUI_MESSAGE_BOX: + gui::message_box::layout(); + break; + case GUI_DIRECT_CONNECTION: + gui::direct_connection::layout(); + break; + } + } +} diff --git a/game/client/game.hh b/game/client/game.hh index 395acc9..649700a 100644 --- a/game/client/game.hh +++ b/game/client/game.hh @@ -1,35 +1,35 @@ -#pragma once - -namespace config -{ -class Boolean; -class String; -class Unsigned; -} // namespace config - -namespace client_game -{ -extern config::Boolean streamer_mode; -extern config::Boolean vertical_sync; -extern config::Boolean world_curvature; -extern config::Unsigned fog_mode; -extern config::String username; -} // namespace client_game - -namespace client_game -{ -extern bool hide_hud; -} // namespace client_game - -namespace client_game -{ -void init(void); -void init_late(void); -void shutdown(void); -void fixed_update(void); -void fixed_update_late(void); -void update(void); -void update_late(void); -void render(void); -void layout(void); -} // namespace client_game +#pragma once + +namespace config +{ +class Boolean; +class String; +class Unsigned; +} // namespace config + +namespace client_game +{ +extern config::Boolean streamer_mode; +extern config::Boolean vertical_sync; +extern config::Boolean world_curvature; +extern config::Unsigned fog_mode; +extern config::String username; +} // namespace client_game + +namespace client_game +{ +extern bool hide_hud; +} // namespace client_game + +namespace client_game +{ +void init(void); +void init_late(void); +void shutdown(void); +void fixed_update(void); +void fixed_update_late(void); +void update(void); +void update_late(void); +void render(void); +void layout(void); +} // namespace client_game diff --git a/game/client/globals.cc b/game/client/globals.cc index 1932675..1cf1aeb 100644 --- a/game/client/globals.cc +++ b/game/client/globals.cc @@ -1,47 +1,47 @@ -#include "client/pch.hh" - -#include "client/globals.hh" - -#include "core/io/config_map.hh" - -#include "client/gui/gui_screen.hh" - -io::ConfigMap globals::client_config; - -GLFWwindow* globals::window; - -float globals::window_frametime; -float globals::window_frametime_avg; -std::uint64_t globals::window_frametime_us; -std::uint64_t globals::window_framecount; - -std::uint64_t globals::fixed_accumulator; - -int globals::width; -int globals::height; -float globals::aspect; - -GLuint globals::world_fbo; -GLuint globals::world_fbo_color; -GLuint globals::world_fbo_depth; - -std::size_t globals::num_drawcalls; -std::size_t globals::num_triangles; - -ENetHost* globals::client_host; - -world::Dimension* globals::dimension = nullptr; -entt::entity globals::player; - -ImFont* globals::font_unscii16; -ImFont* globals::font_unscii8; - -config::KeyBind* globals::gui_keybind_ptr = nullptr; -config::GamepadAxis* globals::gui_gamepad_axis_ptr = nullptr; -config::GamepadButton* globals::gui_gamepad_button_ptr = nullptr; - -unsigned int globals::gui_scale = 0U; -unsigned int globals::gui_screen = GUI_SCREEN_NONE; - -ALCdevice* globals::sound_dev; -ALCcontext* globals::sound_ctx; +#include "client/pch.hh" + +#include "client/globals.hh" + +#include "core/io/config_map.hh" + +#include "client/gui/gui_screen.hh" + +io::ConfigMap globals::client_config; + +GLFWwindow* globals::window; + +float globals::window_frametime; +float globals::window_frametime_avg; +std::uint64_t globals::window_frametime_us; +std::uint64_t globals::window_framecount; + +std::uint64_t globals::fixed_accumulator; + +int globals::width; +int globals::height; +float globals::aspect; + +GLuint globals::world_fbo; +GLuint globals::world_fbo_color; +GLuint globals::world_fbo_depth; + +std::size_t globals::num_drawcalls; +std::size_t globals::num_triangles; + +ENetHost* globals::client_host; + +world::Dimension* globals::dimension = nullptr; +entt::entity globals::player; + +ImFont* globals::font_unscii16; +ImFont* globals::font_unscii8; + +config::KeyBind* globals::gui_keybind_ptr = nullptr; +config::GamepadAxis* globals::gui_gamepad_axis_ptr = nullptr; +config::GamepadButton* globals::gui_gamepad_button_ptr = nullptr; + +unsigned int globals::gui_scale = 0U; +unsigned int globals::gui_screen = GUI_SCREEN_NONE; + +ALCdevice* globals::sound_dev; +ALCcontext* globals::sound_ctx; diff --git a/game/client/globals.hh b/game/client/globals.hh index ba57a9e..41531a9 100644 --- a/game/client/globals.hh +++ b/game/client/globals.hh @@ -1,71 +1,71 @@ -#pragma once - -#include "shared/globals.hh" - -namespace config -{ -class KeyBind; -class GamepadAxis; -class GamepadButton; -} // namespace config - -namespace io -{ -class ConfigMap; -} // namespace io - -struct GLFWwindow; -struct ImFont; - -namespace world -{ -class Dimension; -} // namespace world - -namespace globals -{ -extern io::ConfigMap client_config; - -extern GLFWwindow* window; - -// Some gamesystems that aren't really -// gameplay-oriented might still use client -// framerate to interpolate discrete things -// so it's still a good idea to keep these available -extern float window_frametime; -extern float window_frametime_avg; -extern std::uint64_t window_frametime_us; -extern std::uint64_t window_framecount; - -// https://gafferongames.com/post/fix_your_timestep/ -extern std::uint64_t fixed_accumulator; - -extern int width; -extern int height; -extern float aspect; - -extern GLuint world_fbo; -extern GLuint world_fbo_color; -extern GLuint world_fbo_depth; - -extern std::size_t num_drawcalls; -extern std::size_t num_triangles; - -extern ENetHost* client_host; - -extern world::Dimension* dimension; -extern entt::entity player; - -extern ImFont* font_unscii16; -extern ImFont* font_unscii8; - -extern config::KeyBind* gui_keybind_ptr; -extern config::GamepadAxis* gui_gamepad_axis_ptr; -extern config::GamepadButton* gui_gamepad_button_ptr; - -extern unsigned int gui_scale; -extern unsigned int gui_screen; - -extern ALCdevice* sound_dev; -extern ALCcontext* sound_ctx; -} // namespace globals +#pragma once + +#include "shared/globals.hh" + +namespace config +{ +class KeyBind; +class GamepadAxis; +class GamepadButton; +} // namespace config + +namespace io +{ +class ConfigMap; +} // namespace io + +struct GLFWwindow; +struct ImFont; + +namespace world +{ +class Dimension; +} // namespace world + +namespace globals +{ +extern io::ConfigMap client_config; + +extern GLFWwindow* window; + +// Some gamesystems that aren't really +// gameplay-oriented might still use client +// framerate to interpolate discrete things +// so it's still a good idea to keep these available +extern float window_frametime; +extern float window_frametime_avg; +extern std::uint64_t window_frametime_us; +extern std::uint64_t window_framecount; + +// https://gafferongames.com/post/fix_your_timestep/ +extern std::uint64_t fixed_accumulator; + +extern int width; +extern int height; +extern float aspect; + +extern GLuint world_fbo; +extern GLuint world_fbo_color; +extern GLuint world_fbo_depth; + +extern std::size_t num_drawcalls; +extern std::size_t num_triangles; + +extern ENetHost* client_host; + +extern world::Dimension* dimension; +extern entt::entity player; + +extern ImFont* font_unscii16; +extern ImFont* font_unscii8; + +extern config::KeyBind* gui_keybind_ptr; +extern config::GamepadAxis* gui_gamepad_axis_ptr; +extern config::GamepadButton* gui_gamepad_button_ptr; + +extern unsigned int gui_scale; +extern unsigned int gui_screen; + +extern ALCdevice* sound_dev; +extern ALCcontext* sound_ctx; +} // namespace globals diff --git a/game/client/gui/background.cc b/game/client/gui/background.cc index 50fef01..d1500bb 100644 --- a/game/client/gui/background.cc +++ b/game/client/gui/background.cc @@ -1,39 +1,39 @@ -#include "client/pch.hh" - -#include "client/gui/background.hh" - -#include "core/math/constexpr.hh" - -#include "core/resource/resource.hh" - -#include "client/resource/texture_gui.hh" - -#include "client/globals.hh" - -static resource_ptr texture; - -void gui::background::init(void) -{ - texture = resource::load("textures/gui/background.png", TEXTURE_GUI_LOAD_VFLIP); - - if(texture == nullptr) { - spdlog::critical("background: texture load failed"); - std::terminate(); - } -} - -void gui::background::shutdown(void) -{ - texture = nullptr; -} - -void gui::background::layout(void) -{ - auto viewport = ImGui::GetMainViewport(); - auto draw_list = ImGui::GetBackgroundDrawList(); - - auto scaled_width = 0.75f * static_cast(globals::width / globals::gui_scale); - auto scaled_height = 0.75f * static_cast(globals::height / globals::gui_scale); - auto scale_uv = ImVec2(scaled_width / static_cast(texture->size.x), scaled_height / static_cast(texture->size.y)); - draw_list->AddImage(texture->handle, ImVec2(0.0f, 0.0f), viewport->Size, ImVec2(0.0f, 0.0f), scale_uv); -} +#include "client/pch.hh" + +#include "client/gui/background.hh" + +#include "core/math/constexpr.hh" + +#include "core/resource/resource.hh" + +#include "client/resource/texture_gui.hh" + +#include "client/globals.hh" + +static resource_ptr texture; + +void gui::background::init(void) +{ + texture = resource::load("textures/gui/background.png", TEXTURE_GUI_LOAD_VFLIP); + + if(texture == nullptr) { + spdlog::critical("background: texture load failed"); + std::terminate(); + } +} + +void gui::background::shutdown(void) +{ + texture = nullptr; +} + +void gui::background::layout(void) +{ + auto viewport = ImGui::GetMainViewport(); + auto draw_list = ImGui::GetBackgroundDrawList(); + + auto scaled_width = 0.75f * static_cast(globals::width / globals::gui_scale); + auto scaled_height = 0.75f * static_cast(globals::height / globals::gui_scale); + auto scale_uv = ImVec2(scaled_width / static_cast(texture->size.x), scaled_height / static_cast(texture->size.y)); + draw_list->AddImage(texture->handle, ImVec2(0.0f, 0.0f), viewport->Size, ImVec2(0.0f, 0.0f), scale_uv); +} diff --git a/game/client/gui/background.hh b/game/client/gui/background.hh index 5c72a3f..6145484 100644 --- a/game/client/gui/background.hh +++ b/game/client/gui/background.hh @@ -1,8 +1,8 @@ -#pragma once - -namespace gui::background -{ -void init(void); -void shutdown(void); -void layout(void); -} // namespace gui::background +#pragma once + +namespace gui::background +{ +void init(void); +void shutdown(void); +void layout(void); +} // namespace gui::background diff --git a/game/client/gui/bother.cc b/game/client/gui/bother.cc index d87f220..1bb7097 100644 --- a/game/client/gui/bother.cc +++ b/game/client/gui/bother.cc @@ -1,163 +1,163 @@ -#include "client/pch.hh" - -#include "client/gui/bother.hh" - -#include "shared/protocol.hh" - -#include "client/globals.hh" - -// Maximum amount of peers used for bothering -constexpr static std::size_t BOTHER_PEERS = 4; - -struct BotherQueueItem final { - unsigned int identity; - std::string hostname; - std::uint16_t port; -}; - -static ENetHost* bother_host; -static entt::dispatcher bother_dispatcher; -static std::unordered_set bother_set; -static std::deque bother_queue; - -static void on_status_response_packet(const protocol::StatusResponse& packet) -{ - auto identity = static_cast(reinterpret_cast(packet.peer->data)); - - bother_set.erase(identity); - - gui::BotherResponseEvent event; - event.identity = identity; - event.is_server_unreachable = false; - event.protocol_version = packet.version; - event.num_players = packet.num_players; - event.max_players = packet.max_players; - event.motd = packet.motd; - globals::dispatcher.trigger(event); - - enet_peer_disconnect(packet.peer, protocol::CHANNEL); -} - -void gui::bother::init(void) -{ - bother_host = enet_host_create(nullptr, BOTHER_PEERS, 1, 0, 0); - bother_dispatcher.clear(); - bother_set.clear(); - - bother_dispatcher.sink().connect<&on_status_response_packet>(); -} - -void gui::bother::shutdown(void) -{ - enet_host_destroy(bother_host); - bother_dispatcher.clear(); - bother_set.clear(); -} - -void gui::bother::update_late(void) -{ - unsigned int free_peers = 0U; - - // Figure out how much times we can call - // enet_host_connect and reallistically succeed - for(unsigned int i = 0U; i < bother_host->peerCount; ++i) { - if(bother_host->peers[i].state != ENET_PEER_STATE_DISCONNECTED) { - continue; - } - - free_peers += 1U; - } - - for(unsigned int i = 0U; (i < free_peers) && bother_queue.size(); ++i) { - const auto& item = bother_queue.front(); - - ENetAddress address; - enet_address_set_host(&address, item.hostname.c_str()); - address.port = enet_uint16(item.port); - - if(auto peer = enet_host_connect(bother_host, &address, 1, 0)) { - peer->data = reinterpret_cast(static_cast(item.identity)); - bother_set.insert(item.identity); - enet_host_flush(bother_host); - } - - bother_queue.pop_front(); - } - - ENetEvent enet_event; - - if(0 < enet_host_service(bother_host, &enet_event, 0)) { - if(enet_event.type == ENET_EVENT_TYPE_CONNECT) { - protocol::StatusRequest packet; - packet.version = protocol::VERSION; - protocol::send(enet_event.peer, protocol::encode(packet)); - return; - } - - if(enet_event.type == ENET_EVENT_TYPE_RECEIVE) { - protocol::decode(bother_dispatcher, enet_event.packet, enet_event.peer); - enet_packet_destroy(enet_event.packet); - return; - } - - if(enet_event.type == ENET_EVENT_TYPE_DISCONNECT) { - auto identity = static_cast(reinterpret_cast(enet_event.peer->data)); - - if(bother_set.count(identity)) { - BotherResponseEvent event; - event.identity = identity; - event.is_server_unreachable = true; - globals::dispatcher.trigger(event); - } - - bother_set.erase(identity); - - return; - } - } -} - -void gui::bother::ping(unsigned int identity, std::string_view host, std::uint16_t port) -{ - if(bother_set.count(identity)) { - // Already in the process - return; - } - - for(const auto& item : bother_queue) { - if(item.identity == identity) { - // Already in the queue - return; - } - } - - BotherQueueItem item; - item.identity = identity; - item.hostname = host; - item.port = port; - - bother_queue.push_back(item); -} - -void gui::bother::cancel(unsigned int identity) -{ - bother_set.erase(identity); - - auto item = bother_queue.cbegin(); - - while(item != bother_queue.cend()) { - if(item->identity == identity) { - item = bother_queue.erase(item); - continue; - } - - item = std::next(item); - } - - for(unsigned int i = 0U; i < bother_host->peerCount; ++i) { - if(bother_host->peers[i].data == reinterpret_cast(static_cast(identity))) { - enet_peer_reset(&bother_host->peers[i]); - break; - } - } -} +#include "client/pch.hh" + +#include "client/gui/bother.hh" + +#include "shared/protocol.hh" + +#include "client/globals.hh" + +// Maximum amount of peers used for bothering +constexpr static std::size_t BOTHER_PEERS = 4; + +struct BotherQueueItem final { + unsigned int identity; + std::string hostname; + std::uint16_t port; +}; + +static ENetHost* bother_host; +static entt::dispatcher bother_dispatcher; +static std::unordered_set bother_set; +static std::deque bother_queue; + +static void on_status_response_packet(const protocol::StatusResponse& packet) +{ + auto identity = static_cast(reinterpret_cast(packet.peer->data)); + + bother_set.erase(identity); + + gui::BotherResponseEvent event; + event.identity = identity; + event.is_server_unreachable = false; + event.protocol_version = packet.version; + event.num_players = packet.num_players; + event.max_players = packet.max_players; + event.motd = packet.motd; + globals::dispatcher.trigger(event); + + enet_peer_disconnect(packet.peer, protocol::CHANNEL); +} + +void gui::bother::init(void) +{ + bother_host = enet_host_create(nullptr, BOTHER_PEERS, 1, 0, 0); + bother_dispatcher.clear(); + bother_set.clear(); + + bother_dispatcher.sink().connect<&on_status_response_packet>(); +} + +void gui::bother::shutdown(void) +{ + enet_host_destroy(bother_host); + bother_dispatcher.clear(); + bother_set.clear(); +} + +void gui::bother::update_late(void) +{ + unsigned int free_peers = 0U; + + // Figure out how much times we can call + // enet_host_connect and reallistically succeed + for(unsigned int i = 0U; i < bother_host->peerCount; ++i) { + if(bother_host->peers[i].state != ENET_PEER_STATE_DISCONNECTED) { + continue; + } + + free_peers += 1U; + } + + for(unsigned int i = 0U; (i < free_peers) && bother_queue.size(); ++i) { + const auto& item = bother_queue.front(); + + ENetAddress address; + enet_address_set_host(&address, item.hostname.c_str()); + address.port = enet_uint16(item.port); + + if(auto peer = enet_host_connect(bother_host, &address, 1, 0)) { + peer->data = reinterpret_cast(static_cast(item.identity)); + bother_set.insert(item.identity); + enet_host_flush(bother_host); + } + + bother_queue.pop_front(); + } + + ENetEvent enet_event; + + if(0 < enet_host_service(bother_host, &enet_event, 0)) { + if(enet_event.type == ENET_EVENT_TYPE_CONNECT) { + protocol::StatusRequest packet; + packet.version = protocol::VERSION; + protocol::send(enet_event.peer, protocol::encode(packet)); + return; + } + + if(enet_event.type == ENET_EVENT_TYPE_RECEIVE) { + protocol::decode(bother_dispatcher, enet_event.packet, enet_event.peer); + enet_packet_destroy(enet_event.packet); + return; + } + + if(enet_event.type == ENET_EVENT_TYPE_DISCONNECT) { + auto identity = static_cast(reinterpret_cast(enet_event.peer->data)); + + if(bother_set.count(identity)) { + BotherResponseEvent event; + event.identity = identity; + event.is_server_unreachable = true; + globals::dispatcher.trigger(event); + } + + bother_set.erase(identity); + + return; + } + } +} + +void gui::bother::ping(unsigned int identity, std::string_view host, std::uint16_t port) +{ + if(bother_set.count(identity)) { + // Already in the process + return; + } + + for(const auto& item : bother_queue) { + if(item.identity == identity) { + // Already in the queue + return; + } + } + + BotherQueueItem item; + item.identity = identity; + item.hostname = host; + item.port = port; + + bother_queue.push_back(item); +} + +void gui::bother::cancel(unsigned int identity) +{ + bother_set.erase(identity); + + auto item = bother_queue.cbegin(); + + while(item != bother_queue.cend()) { + if(item->identity == identity) { + item = bother_queue.erase(item); + continue; + } + + item = std::next(item); + } + + for(unsigned int i = 0U; i < bother_host->peerCount; ++i) { + if(bother_host->peers[i].data == reinterpret_cast(static_cast(identity))) { + enet_peer_reset(&bother_host->peers[i]); + break; + } + } +} diff --git a/game/client/gui/bother.hh b/game/client/gui/bother.hh index c83294c..fc5bab4 100644 --- a/game/client/gui/bother.hh +++ b/game/client/gui/bother.hh @@ -1,22 +1,22 @@ -#pragma once - -namespace gui -{ -struct BotherResponseEvent final { - unsigned int identity; - bool is_server_unreachable; - std::uint32_t protocol_version; - std::uint16_t num_players; - std::uint16_t max_players; - std::string motd; -}; -} // namespace gui - -namespace gui::bother -{ -void init(void); -void shutdown(void); -void update_late(void); -void ping(unsigned int identity, std::string_view host, std::uint16_t port); -void cancel(unsigned int identity); -} // namespace gui::bother +#pragma once + +namespace gui +{ +struct BotherResponseEvent final { + unsigned int identity; + bool is_server_unreachable; + std::uint32_t protocol_version; + std::uint16_t num_players; + std::uint16_t max_players; + std::string motd; +}; +} // namespace gui + +namespace gui::bother +{ +void init(void); +void shutdown(void); +void update_late(void); +void ping(unsigned int identity, std::string_view host, std::uint16_t port); +void cancel(unsigned int identity); +} // namespace gui::bother diff --git a/game/client/gui/chat.cc b/game/client/gui/chat.cc index 6e4498b..aaee8c6 100644 --- a/game/client/gui/chat.cc +++ b/game/client/gui/chat.cc @@ -1,273 +1,273 @@ -#include "client/pch.hh" - -#include "client/gui/chat.hh" - -#include "core/config/number.hh" -#include "core/config/string.hh" - -#include "core/io/config_map.hh" - -#include "core/resource/resource.hh" - -#include "core/utils/string.hh" - -#include "shared/protocol.hh" - -#include "client/config/keybind.hh" - -#include "client/gui/gui_screen.hh" -#include "client/gui/imdraw_ext.hh" -#include "client/gui/language.hh" -#include "client/gui/settings.hh" - -#include "client/io/glfw.hh" - -#include "client/resource/sound_effect.hh" - -#include "client/sound/sound.hh" - -#include "client/game.hh" -#include "client/globals.hh" -#include "client/session.hh" - -constexpr static ImGuiWindowFlags WINDOW_FLAGS = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration; -constexpr static unsigned int MAX_HISTORY_SIZE = 128U; - -struct GuiChatMessage final { - std::uint64_t spawn; - std::string text; - ImVec4 color; -}; - -static config::KeyBind key_chat(GLFW_KEY_ENTER); -static config::Unsigned history_size(32U, 0U, MAX_HISTORY_SIZE); - -static std::deque history; -static std::string chat_input; -static bool needs_focus; - -static resource_ptr sfx_chat_message; - -static void append_text_message(const std::string& sender, const std::string& text) -{ - GuiChatMessage message; - message.spawn = globals::curtime; - message.text = std::format("<{}> {}", sender, text); - message.color = ImGui::GetStyleColorVec4(ImGuiCol_Text); - history.push_back(message); - - if(sfx_chat_message && session::is_ingame()) { - sound::play_ui(sfx_chat_message, false, 1.0f); - } -} - -static void append_player_join(const std::string& sender) -{ - GuiChatMessage message; - message.spawn = globals::curtime; - message.text = std::format("{} {}", sender, gui::language::resolve("chat.client_join")); - message.color = ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget); - history.push_back(message); - - if(sfx_chat_message && session::is_ingame()) { - sound::play_ui(sfx_chat_message, false, 1.0f); - } -} - -static void append_player_leave(const std::string& sender, const std::string& reason) -{ - GuiChatMessage message; - message.spawn = globals::curtime; - message.text = std::format("{} {} ({})", sender, gui::language::resolve("chat.client_left"), gui::language::resolve(reason.c_str())); - message.color = ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget); - history.push_back(message); - - if(sfx_chat_message && session::is_ingame()) { - sound::play_ui(sfx_chat_message, false, 1.0f); - } -} - -static void on_chat_message_packet(const protocol::ChatMessage& packet) -{ - if(packet.type == protocol::ChatMessage::TEXT_MESSAGE) { - append_text_message(packet.sender, packet.message); - return; - } - - if(packet.type == protocol::ChatMessage::PLAYER_JOIN) { - append_player_join(packet.sender); - return; - } - - if(packet.type == protocol::ChatMessage::PLAYER_LEAVE) { - append_player_leave(packet.sender, packet.message); - return; - } -} - -static void on_glfw_key(const io::GlfwKeyEvent& event) -{ - if(event.action == GLFW_PRESS) { - if((event.key == GLFW_KEY_ENTER) && (globals::gui_screen == GUI_CHAT)) { - if(!utils::is_whitespace(chat_input)) { - protocol::ChatMessage packet; - packet.type = protocol::ChatMessage::TEXT_MESSAGE; - packet.sender = client_game::username.get(); - packet.message = chat_input; - - protocol::send(session::peer, protocol::encode(packet)); - } - - globals::gui_screen = GUI_SCREEN_NONE; - - chat_input.clear(); - - return; - } - - if((event.key == GLFW_KEY_ESCAPE) && (globals::gui_screen == GUI_CHAT)) { - globals::gui_screen = GUI_SCREEN_NONE; - return; - } - - if(key_chat.equals(event.key) && !globals::gui_screen) { - globals::gui_screen = GUI_CHAT; - needs_focus = true; - return; - } - } -} - -void gui::client_chat::init(void) -{ - globals::client_config.add_value("chat.key", key_chat); - globals::client_config.add_value("chat.history_size", history_size); - - settings::add_keybind(2, key_chat, settings_location::KEYBOARD_MISC, "key.chat"); - settings::add_slider(1, history_size, settings_location::VIDEO_GUI, "chat.history_size", false); - - globals::dispatcher.sink().connect<&on_chat_message_packet>(); - globals::dispatcher.sink().connect<&on_glfw_key>(); - - sfx_chat_message = resource::load("sounds/ui/chat_message.wav"); -} - -void gui::client_chat::init_late(void) -{ -} - -void gui::client_chat::shutdown(void) -{ - sfx_chat_message = nullptr; -} - -void gui::client_chat::update(void) -{ - while(history.size() > history_size.get_value()) { - history.pop_front(); - } -} - -void gui::client_chat::layout(void) -{ - auto viewport = ImGui::GetMainViewport(); - auto window_start = ImVec2(0.0f, 0.0f); - auto window_size = ImVec2(0.75f * viewport->Size.x, viewport->Size.y); - - ImGui::SetNextWindowPos(window_start); - ImGui::SetNextWindowSize(window_size); - - ImGui::PushFont(globals::font_unscii16, 8.0f); - - if(!ImGui::Begin("###chat", nullptr, WINDOW_FLAGS)) { - ImGui::End(); - return; - } - - auto& padding = ImGui::GetStyle().FramePadding; - auto& spacing = ImGui::GetStyle().ItemSpacing; - auto font = ImGui::GetFont(); - - auto draw_list = ImGui::GetWindowDrawList(); - - // The text input widget occupies the bottom part - // of the chat window, we need to reserve some space for it - auto ypos = window_size.y - 2.5f * ImGui::GetFontSize() - 2.0f * padding.y - 2.0f * spacing.y; - - if(globals::gui_screen == GUI_CHAT) { - if(needs_focus) { - ImGui::SetKeyboardFocusHere(); - needs_focus = false; - } - - ImGui::SetNextItemWidth(window_size.x + 32.0f * padding.x); - ImGui::SetCursorScreenPos(ImVec2(padding.x, ypos)); - ImGui::InputText("###chat.input", &chat_input); - } - - if(!client_game::hide_hud && ((globals::gui_screen == GUI_SCREEN_NONE) || (globals::gui_screen == GUI_CHAT))) { - for(auto it = history.crbegin(); it < history.crend(); ++it) { - auto text_size = ImGui::CalcTextSize(it->text.c_str(), it->text.c_str() + it->text.size(), false, window_size.x); - auto rect_size = ImVec2(window_size.x, text_size.y + 2.0f * padding.y); - - auto rect_pos = ImVec2(padding.x, ypos - text_size.y - 2.0f * padding.y); - auto rect_end = ImVec2(rect_pos.x + rect_size.x, rect_pos.y + rect_size.y); - auto text_pos = ImVec2(rect_pos.x + padding.x, rect_pos.y + padding.y); - - auto fadeout_seconds = 10.0f; - auto fadeout = std::exp(-1.0f * std::pow(1.0e-6 * static_cast(globals::curtime - it->spawn) / fadeout_seconds, 10.0f)); - - float rect_alpha; - float text_alpha; - - if(globals::gui_screen == GUI_CHAT) { - rect_alpha = 0.75f; - text_alpha = 1.00f; - } - else { - rect_alpha = 0.50f * fadeout; - text_alpha = 1.00f * fadeout; - } - - auto rect_col = ImGui::GetColorU32(ImGuiCol_FrameBg, rect_alpha); - auto text_col = ImGui::GetColorU32(ImVec4(it->color.x, it->color.y, it->color.z, it->color.w * text_alpha)); - auto shadow_col = ImGui::GetColorU32(ImVec4(0.0f, 0.0f, 0.0f, text_alpha)); - - draw_list->AddRectFilled(rect_pos, rect_end, rect_col); - - imdraw_ext::text_shadow_w(it->text, text_pos, text_col, shadow_col, font, draw_list, 8.0f, window_size.x); - - ypos -= rect_size.y; - } - } - - ImGui::End(); - ImGui::PopFont(); -} - -void gui::client_chat::clear(void) -{ - history.clear(); -} - -void gui::client_chat::refresh_timings(void) -{ - for(auto it = history.begin(); it < history.end(); ++it) { - // Reset the spawn time so the fadeout timer - // is reset; SpawnPlayer handler might call this - it->spawn = globals::curtime; - } -} - -void gui::client_chat::print(const std::string& text) -{ - GuiChatMessage message = {}; - message.spawn = globals::curtime; - message.text = text; - message.color = ImGui::GetStyleColorVec4(ImGuiCol_Text); - history.push_back(message); - - if(sfx_chat_message && session::is_ingame()) { - sound::play_ui(sfx_chat_message, false, 1.0f); - } -} +#include "client/pch.hh" + +#include "client/gui/chat.hh" + +#include "core/config/number.hh" +#include "core/config/string.hh" + +#include "core/io/config_map.hh" + +#include "core/resource/resource.hh" + +#include "core/utils/string.hh" + +#include "shared/protocol.hh" + +#include "client/config/keybind.hh" + +#include "client/gui/gui_screen.hh" +#include "client/gui/imdraw_ext.hh" +#include "client/gui/language.hh" +#include "client/gui/settings.hh" + +#include "client/io/glfw.hh" + +#include "client/resource/sound_effect.hh" + +#include "client/sound/sound.hh" + +#include "client/game.hh" +#include "client/globals.hh" +#include "client/session.hh" + +constexpr static ImGuiWindowFlags WINDOW_FLAGS = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration; +constexpr static unsigned int MAX_HISTORY_SIZE = 128U; + +struct GuiChatMessage final { + std::uint64_t spawn; + std::string text; + ImVec4 color; +}; + +static config::KeyBind key_chat(GLFW_KEY_ENTER); +static config::Unsigned history_size(32U, 0U, MAX_HISTORY_SIZE); + +static std::deque history; +static std::string chat_input; +static bool needs_focus; + +static resource_ptr sfx_chat_message; + +static void append_text_message(const std::string& sender, const std::string& text) +{ + GuiChatMessage message; + message.spawn = globals::curtime; + message.text = std::format("<{}> {}", sender, text); + message.color = ImGui::GetStyleColorVec4(ImGuiCol_Text); + history.push_back(message); + + if(sfx_chat_message && session::is_ingame()) { + sound::play_ui(sfx_chat_message, false, 1.0f); + } +} + +static void append_player_join(const std::string& sender) +{ + GuiChatMessage message; + message.spawn = globals::curtime; + message.text = std::format("{} {}", sender, gui::language::resolve("chat.client_join")); + message.color = ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget); + history.push_back(message); + + if(sfx_chat_message && session::is_ingame()) { + sound::play_ui(sfx_chat_message, false, 1.0f); + } +} + +static void append_player_leave(const std::string& sender, const std::string& reason) +{ + GuiChatMessage message; + message.spawn = globals::curtime; + message.text = std::format("{} {} ({})", sender, gui::language::resolve("chat.client_left"), gui::language::resolve(reason.c_str())); + message.color = ImGui::GetStyleColorVec4(ImGuiCol_DragDropTarget); + history.push_back(message); + + if(sfx_chat_message && session::is_ingame()) { + sound::play_ui(sfx_chat_message, false, 1.0f); + } +} + +static void on_chat_message_packet(const protocol::ChatMessage& packet) +{ + if(packet.type == protocol::ChatMessage::TEXT_MESSAGE) { + append_text_message(packet.sender, packet.message); + return; + } + + if(packet.type == protocol::ChatMessage::PLAYER_JOIN) { + append_player_join(packet.sender); + return; + } + + if(packet.type == protocol::ChatMessage::PLAYER_LEAVE) { + append_player_leave(packet.sender, packet.message); + return; + } +} + +static void on_glfw_key(const io::GlfwKeyEvent& event) +{ + if(event.action == GLFW_PRESS) { + if((event.key == GLFW_KEY_ENTER) && (globals::gui_screen == GUI_CHAT)) { + if(!utils::is_whitespace(chat_input)) { + protocol::ChatMessage packet; + packet.type = protocol::ChatMessage::TEXT_MESSAGE; + packet.sender = client_game::username.get(); + packet.message = chat_input; + + protocol::send(session::peer, protocol::encode(packet)); + } + + globals::gui_screen = GUI_SCREEN_NONE; + + chat_input.clear(); + + return; + } + + if((event.key == GLFW_KEY_ESCAPE) && (globals::gui_screen == GUI_CHAT)) { + globals::gui_screen = GUI_SCREEN_NONE; + return; + } + + if(key_chat.equals(event.key) && !globals::gui_screen) { + globals::gui_screen = GUI_CHAT; + needs_focus = true; + return; + } + } +} + +void gui::client_chat::init(void) +{ + globals::client_config.add_value("chat.key", key_chat); + globals::client_config.add_value("chat.history_size", history_size); + + settings::add_keybind(2, key_chat, settings_location::KEYBOARD_MISC, "key.chat"); + settings::add_slider(1, history_size, settings_location::VIDEO_GUI, "chat.history_size", false); + + globals::dispatcher.sink().connect<&on_chat_message_packet>(); + globals::dispatcher.sink().connect<&on_glfw_key>(); + + sfx_chat_message = resource::load("sounds/ui/chat_message.wav"); +} + +void gui::client_chat::init_late(void) +{ +} + +void gui::client_chat::shutdown(void) +{ + sfx_chat_message = nullptr; +} + +void gui::client_chat::update(void) +{ + while(history.size() > history_size.get_value()) { + history.pop_front(); + } +} + +void gui::client_chat::layout(void) +{ + auto viewport = ImGui::GetMainViewport(); + auto window_start = ImVec2(0.0f, 0.0f); + auto window_size = ImVec2(0.75f * viewport->Size.x, viewport->Size.y); + + ImGui::SetNextWindowPos(window_start); + ImGui::SetNextWindowSize(window_size); + + ImGui::PushFont(globals::font_unscii16, 8.0f); + + if(!ImGui::Begin("###chat", nullptr, WINDOW_FLAGS)) { + ImGui::End(); + return; + } + + auto& padding = ImGui::GetStyle().FramePadding; + auto& spacing = ImGui::GetStyle().ItemSpacing; + auto font = ImGui::GetFont(); + + auto draw_list = ImGui::GetWindowDrawList(); + + // The text input widget occupies the bottom part + // of the chat window, we need to reserve some space for it + auto ypos = window_size.y - 2.5f * ImGui::GetFontSize() - 2.0f * padding.y - 2.0f * spacing.y; + + if(globals::gui_screen == GUI_CHAT) { + if(needs_focus) { + ImGui::SetKeyboardFocusHere(); + needs_focus = false; + } + + ImGui::SetNextItemWidth(window_size.x + 32.0f * padding.x); + ImGui::SetCursorScreenPos(ImVec2(padding.x, ypos)); + ImGui::InputText("###chat.input", &chat_input); + } + + if(!client_game::hide_hud && ((globals::gui_screen == GUI_SCREEN_NONE) || (globals::gui_screen == GUI_CHAT))) { + for(auto it = history.crbegin(); it < history.crend(); ++it) { + auto text_size = ImGui::CalcTextSize(it->text.c_str(), it->text.c_str() + it->text.size(), false, window_size.x); + auto rect_size = ImVec2(window_size.x, text_size.y + 2.0f * padding.y); + + auto rect_pos = ImVec2(padding.x, ypos - text_size.y - 2.0f * padding.y); + auto rect_end = ImVec2(rect_pos.x + rect_size.x, rect_pos.y + rect_size.y); + auto text_pos = ImVec2(rect_pos.x + padding.x, rect_pos.y + padding.y); + + auto fadeout_seconds = 10.0f; + auto fadeout = std::exp(-1.0f * std::pow(1.0e-6 * static_cast(globals::curtime - it->spawn) / fadeout_seconds, 10.0f)); + + float rect_alpha; + float text_alpha; + + if(globals::gui_screen == GUI_CHAT) { + rect_alpha = 0.75f; + text_alpha = 1.00f; + } + else { + rect_alpha = 0.50f * fadeout; + text_alpha = 1.00f * fadeout; + } + + auto rect_col = ImGui::GetColorU32(ImGuiCol_FrameBg, rect_alpha); + auto text_col = ImGui::GetColorU32(ImVec4(it->color.x, it->color.y, it->color.z, it->color.w * text_alpha)); + auto shadow_col = ImGui::GetColorU32(ImVec4(0.0f, 0.0f, 0.0f, text_alpha)); + + draw_list->AddRectFilled(rect_pos, rect_end, rect_col); + + imdraw_ext::text_shadow_w(it->text, text_pos, text_col, shadow_col, font, draw_list, 8.0f, window_size.x); + + ypos -= rect_size.y; + } + } + + ImGui::End(); + ImGui::PopFont(); +} + +void gui::client_chat::clear(void) +{ + history.clear(); +} + +void gui::client_chat::refresh_timings(void) +{ + for(auto it = history.begin(); it < history.end(); ++it) { + // Reset the spawn time so the fadeout timer + // is reset; SpawnPlayer handler might call this + it->spawn = globals::curtime; + } +} + +void gui::client_chat::print(const std::string& text) +{ + GuiChatMessage message = {}; + message.spawn = globals::curtime; + message.text = text; + message.color = ImGui::GetStyleColorVec4(ImGuiCol_Text); + history.push_back(message); + + if(sfx_chat_message && session::is_ingame()) { + sound::play_ui(sfx_chat_message, false, 1.0f); + } +} diff --git a/game/client/gui/chat.hh b/game/client/gui/chat.hh index 6a3ea33..2fc6fb3 100644 --- a/game/client/gui/chat.hh +++ b/game/client/gui/chat.hh @@ -1,17 +1,17 @@ -#pragma once - -namespace gui::client_chat -{ -void init(void); -void init_late(void); -void shutdown(void); -void update(void); -void layout(void); -} // namespace gui::client_chat - -namespace gui::client_chat -{ -void clear(void); -void refresh_timings(void); -void print(const std::string& string); -} // namespace gui::client_chat +#pragma once + +namespace gui::client_chat +{ +void init(void); +void init_late(void); +void shutdown(void); +void update(void); +void layout(void); +} // namespace gui::client_chat + +namespace gui::client_chat +{ +void clear(void); +void refresh_timings(void); +void print(const std::string& string); +} // namespace gui::client_chat diff --git a/game/client/gui/crosshair.cc b/game/client/gui/crosshair.cc index 29b5fe5..b5650a9 100644 --- a/game/client/gui/crosshair.cc +++ b/game/client/gui/crosshair.cc @@ -1,43 +1,43 @@ -#include "client/pch.hh" - -#include "client/gui/crosshair.hh" - -#include "core/math/constexpr.hh" - -#include "core/resource/resource.hh" - -#include "client/resource/texture_gui.hh" - -#include "client/globals.hh" -#include "client/session.hh" - -static resource_ptr texture; - -void gui::crosshair::init(void) -{ - texture = resource::load( - "textures/gui/hud_crosshair.png", TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T | TEXTURE_GUI_LOAD_VFLIP); - - if(texture == nullptr) { - spdlog::critical("crosshair: texture load failed"); - std::terminate(); - } -} - -void gui::crosshair::shutdown(void) -{ - texture = nullptr; -} - -void gui::crosshair::layout(void) -{ - auto viewport = ImGui::GetMainViewport(); - auto draw_list = ImGui::GetForegroundDrawList(); - - auto scaled_width = math::max(texture->size.x, globals::gui_scale * texture->size.x / 2); - auto scaled_height = math::max(texture->size.y, globals::gui_scale * texture->size.y / 2); - auto start = ImVec2( - static_cast(0.5f * viewport->Size.x) - (scaled_width / 2), static_cast(0.5f * viewport->Size.y) - (scaled_height / 2)); - auto end = ImVec2(start.x + scaled_width, start.y + scaled_height); - draw_list->AddImage(texture->handle, start, end); -} +#include "client/pch.hh" + +#include "client/gui/crosshair.hh" + +#include "core/math/constexpr.hh" + +#include "core/resource/resource.hh" + +#include "client/resource/texture_gui.hh" + +#include "client/globals.hh" +#include "client/session.hh" + +static resource_ptr texture; + +void gui::crosshair::init(void) +{ + texture = resource::load("textures/gui/hud_crosshair.png", + TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T | TEXTURE_GUI_LOAD_VFLIP); + + if(texture == nullptr) { + spdlog::critical("crosshair: texture load failed"); + std::terminate(); + } +} + +void gui::crosshair::shutdown(void) +{ + texture = nullptr; +} + +void gui::crosshair::layout(void) +{ + auto viewport = ImGui::GetMainViewport(); + auto draw_list = ImGui::GetForegroundDrawList(); + + auto scaled_width = math::max(texture->size.x, globals::gui_scale * texture->size.x / 2); + auto scaled_height = math::max(texture->size.y, globals::gui_scale * texture->size.y / 2); + auto start = ImVec2(static_cast(0.5f * viewport->Size.x) - (scaled_width / 2), + static_cast(0.5f * viewport->Size.y) - (scaled_height / 2)); + auto end = ImVec2(start.x + scaled_width, start.y + scaled_height); + draw_list->AddImage(texture->handle, start, end); +} diff --git a/game/client/gui/crosshair.hh b/game/client/gui/crosshair.hh index 589727e..dca5725 100644 --- a/game/client/gui/crosshair.hh +++ b/game/client/gui/crosshair.hh @@ -1,8 +1,8 @@ -#pragma once - -namespace gui::crosshair -{ -void init(void); -void shutdown(void); -void layout(void); -} // namespace gui::crosshair +#pragma once + +namespace gui::crosshair +{ +void init(void); +void shutdown(void); +void layout(void); +} // namespace gui::crosshair diff --git a/game/client/gui/direct_connection.cc b/game/client/gui/direct_connection.cc index 37372e2..dfbd05b 100644 --- a/game/client/gui/direct_connection.cc +++ b/game/client/gui/direct_connection.cc @@ -1,145 +1,145 @@ -#include "client/pch.hh" - -#include "client/gui/direct_connection.hh" - -#include "core/config/boolean.hh" - -#include "core/utils/string.hh" - -#include "shared/protocol.hh" - -#include "client/gui/gui_screen.hh" -#include "client/gui/language.hh" - -#include "client/io/glfw.hh" - -#include "client/game.hh" -#include "client/globals.hh" -#include "client/session.hh" - -constexpr static ImGuiWindowFlags WINDOW_FLAGS = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration; - -static std::string str_title; -static std::string str_connect; -static std::string str_cancel; - -static std::string str_hostname; -static std::string str_password; - -static std::string direct_hostname; -static std::string direct_password; - -static void on_glfw_key(const io::GlfwKeyEvent& event) -{ - if((event.key == GLFW_KEY_ESCAPE) && (event.action == GLFW_PRESS)) { - if(globals::gui_screen == GUI_DIRECT_CONNECTION) { - globals::gui_screen = GUI_PLAY_MENU; - return; - } - } -} - -static void on_language_set(const gui::LanguageSetEvent& event) -{ - str_title = gui::language::resolve("direct_connection.title"); - str_connect = gui::language::resolve_gui("direct_connection.connect"); - str_cancel = gui::language::resolve_gui("direct_connection.cancel"); - - str_hostname = gui::language::resolve("direct_connection.hostname"); - str_password = gui::language::resolve("direct_connection.password"); -} - -static void connect_to_server(void) -{ - auto parts = utils::split(direct_hostname, ":"); - std::string parsed_hostname; - std::uint16_t parsed_port; - - if(!parts[0].empty()) { - parsed_hostname = parts[0]; - } - else { - parsed_hostname = std::string("localhost"); - } - - if(parts.size() >= 2) { - parsed_port = math::clamp(strtoul(parts[1].c_str(), nullptr, 10), 1024, UINT16_MAX); - } - else { - parsed_port = protocol::PORT; - } - - session::connect(parsed_hostname.c_str(), parsed_port, direct_password.c_str()); -} - -void gui::direct_connection::init(void) -{ - globals::dispatcher.sink().connect<&on_glfw_key>(); - globals::dispatcher.sink().connect<&on_language_set>(); -} - -void gui::direct_connection::layout(void) -{ - auto viewport = ImGui::GetMainViewport(); - auto window_start = ImVec2(0.25f * viewport->Size.x, 0.20f * viewport->Size.y); - auto window_size = ImVec2(0.50f * viewport->Size.x, 0.80f * viewport->Size.y); - - ImGui::SetNextWindowPos(window_start); - ImGui::SetNextWindowSize(window_size); - - if(ImGui::Begin("###UIDirectConnect", nullptr, WINDOW_FLAGS)) { - const float title_width = ImGui::CalcTextSize(str_title.c_str()).x; - ImGui::SetCursorPosX(0.5f * (window_size.x - title_width)); - ImGui::TextUnformatted(str_title.c_str()); - - ImGui::Dummy(ImVec2(0.0f, 16.0f * globals::gui_scale)); - - ImGuiInputTextFlags hostname_flags = ImGuiInputTextFlags_CharsNoBlank; - - if(client_game::streamer_mode.get_value()) { - // Hide server hostname to avoid things like - // followers flooding the server that is streamed online - hostname_flags |= ImGuiInputTextFlags_Password; - } - - auto avail_width = ImGui::GetContentRegionAvail().x; - - ImGui::PushItemWidth(avail_width); - - ImGui::InputText("###UIDirectConnect_hostname", &direct_hostname, hostname_flags); - - if(ImGui::BeginItemTooltip()) { - ImGui::PushTextWrapPos(ImGui::GetFontSize() * 16.0f); - ImGui::TextUnformatted(str_hostname.c_str()); - ImGui::PopTextWrapPos(); - ImGui::EndTooltip(); - } - - ImGui::InputText("###UIDirectConnect_password", &direct_password, ImGuiInputTextFlags_Password); - - if(ImGui::BeginItemTooltip()) { - ImGui::PushTextWrapPos(ImGui::GetFontSize() * 16.0f); - ImGui::TextUnformatted(str_password.c_str()); - ImGui::PopTextWrapPos(); - ImGui::EndTooltip(); - } - - ImGui::PopItemWidth(); - - ImGui::Dummy(ImVec2(0.0f, 4.0f * globals::gui_scale)); - - ImGui::BeginDisabled(utils::is_whitespace(direct_hostname)); - - if(ImGui::Button(str_connect.c_str(), ImVec2(avail_width, 0.0f))) { - connect_to_server(); - } - - ImGui::EndDisabled(); - - if(ImGui::Button(str_cancel.c_str(), ImVec2(avail_width, 0.0f))) { - globals::gui_screen = GUI_PLAY_MENU; - } - } - - ImGui::End(); -} +#include "client/pch.hh" + +#include "client/gui/direct_connection.hh" + +#include "core/config/boolean.hh" + +#include "core/utils/string.hh" + +#include "shared/protocol.hh" + +#include "client/gui/gui_screen.hh" +#include "client/gui/language.hh" + +#include "client/io/glfw.hh" + +#include "client/game.hh" +#include "client/globals.hh" +#include "client/session.hh" + +constexpr static ImGuiWindowFlags WINDOW_FLAGS = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration; + +static std::string str_title; +static std::string str_connect; +static std::string str_cancel; + +static std::string str_hostname; +static std::string str_password; + +static std::string direct_hostname; +static std::string direct_password; + +static void on_glfw_key(const io::GlfwKeyEvent& event) +{ + if((event.key == GLFW_KEY_ESCAPE) && (event.action == GLFW_PRESS)) { + if(globals::gui_screen == GUI_DIRECT_CONNECTION) { + globals::gui_screen = GUI_PLAY_MENU; + return; + } + } +} + +static void on_language_set(const gui::LanguageSetEvent& event) +{ + str_title = gui::language::resolve("direct_connection.title"); + str_connect = gui::language::resolve_gui("direct_connection.connect"); + str_cancel = gui::language::resolve_gui("direct_connection.cancel"); + + str_hostname = gui::language::resolve("direct_connection.hostname"); + str_password = gui::language::resolve("direct_connection.password"); +} + +static void connect_to_server(void) +{ + auto parts = utils::split(direct_hostname, ":"); + std::string parsed_hostname; + std::uint16_t parsed_port; + + if(!parts[0].empty()) { + parsed_hostname = parts[0]; + } + else { + parsed_hostname = std::string("localhost"); + } + + if(parts.size() >= 2) { + parsed_port = math::clamp(strtoul(parts[1].c_str(), nullptr, 10), 1024, UINT16_MAX); + } + else { + parsed_port = protocol::PORT; + } + + session::connect(parsed_hostname.c_str(), parsed_port, direct_password.c_str()); +} + +void gui::direct_connection::init(void) +{ + globals::dispatcher.sink().connect<&on_glfw_key>(); + globals::dispatcher.sink().connect<&on_language_set>(); +} + +void gui::direct_connection::layout(void) +{ + auto viewport = ImGui::GetMainViewport(); + auto window_start = ImVec2(0.25f * viewport->Size.x, 0.20f * viewport->Size.y); + auto window_size = ImVec2(0.50f * viewport->Size.x, 0.80f * viewport->Size.y); + + ImGui::SetNextWindowPos(window_start); + ImGui::SetNextWindowSize(window_size); + + if(ImGui::Begin("###UIDirectConnect", nullptr, WINDOW_FLAGS)) { + const float title_width = ImGui::CalcTextSize(str_title.c_str()).x; + ImGui::SetCursorPosX(0.5f * (window_size.x - title_width)); + ImGui::TextUnformatted(str_title.c_str()); + + ImGui::Dummy(ImVec2(0.0f, 16.0f * globals::gui_scale)); + + ImGuiInputTextFlags hostname_flags = ImGuiInputTextFlags_CharsNoBlank; + + if(client_game::streamer_mode.get_value()) { + // Hide server hostname to avoid things like + // followers flooding the server that is streamed online + hostname_flags |= ImGuiInputTextFlags_Password; + } + + auto avail_width = ImGui::GetContentRegionAvail().x; + + ImGui::PushItemWidth(avail_width); + + ImGui::InputText("###UIDirectConnect_hostname", &direct_hostname, hostname_flags); + + if(ImGui::BeginItemTooltip()) { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 16.0f); + ImGui::TextUnformatted(str_hostname.c_str()); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } + + ImGui::InputText("###UIDirectConnect_password", &direct_password, ImGuiInputTextFlags_Password); + + if(ImGui::BeginItemTooltip()) { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 16.0f); + ImGui::TextUnformatted(str_password.c_str()); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } + + ImGui::PopItemWidth(); + + ImGui::Dummy(ImVec2(0.0f, 4.0f * globals::gui_scale)); + + ImGui::BeginDisabled(utils::is_whitespace(direct_hostname)); + + if(ImGui::Button(str_connect.c_str(), ImVec2(avail_width, 0.0f))) { + connect_to_server(); + } + + ImGui::EndDisabled(); + + if(ImGui::Button(str_cancel.c_str(), ImVec2(avail_width, 0.0f))) { + globals::gui_screen = GUI_PLAY_MENU; + } + } + + ImGui::End(); +} diff --git a/game/client/gui/direct_connection.hh b/game/client/gui/direct_connection.hh index aa02d7c..c63156b 100644 --- a/game/client/gui/direct_connection.hh +++ b/game/client/gui/direct_connection.hh @@ -1,7 +1,7 @@ -#pragma once - -namespace gui::direct_connection -{ -void init(void); -void layout(void); -} // namespace gui::direct_connection +#pragma once + +namespace gui::direct_connection +{ +void init(void); +void layout(void); +} // namespace gui::direct_connection diff --git a/game/client/gui/gui_screen.hh b/game/client/gui/gui_screen.hh index 2eae310..c29f701 100644 --- a/game/client/gui/gui_screen.hh +++ b/game/client/gui/gui_screen.hh @@ -1,10 +1,10 @@ -#pragma once - -constexpr static unsigned int GUI_SCREEN_NONE = 0x0000U; -constexpr static unsigned int GUI_MAIN_MENU = 0x0001U; -constexpr static unsigned int GUI_PLAY_MENU = 0x0002U; -constexpr static unsigned int GUI_SETTINGS = 0x0003U; -constexpr static unsigned int GUI_PROGRESS_BAR = 0x0004U; -constexpr static unsigned int GUI_MESSAGE_BOX = 0x0005U; -constexpr static unsigned int GUI_CHAT = 0x0006U; -constexpr static unsigned int GUI_DIRECT_CONNECTION = 0x0007U; +#pragma once + +constexpr static unsigned int GUI_SCREEN_NONE = 0x0000U; +constexpr static unsigned int GUI_MAIN_MENU = 0x0001U; +constexpr static unsigned int GUI_PLAY_MENU = 0x0002U; +constexpr static unsigned int GUI_SETTINGS = 0x0003U; +constexpr static unsigned int GUI_PROGRESS_BAR = 0x0004U; +constexpr static unsigned int GUI_MESSAGE_BOX = 0x0005U; +constexpr static unsigned int GUI_CHAT = 0x0006U; +constexpr static unsigned int GUI_DIRECT_CONNECTION = 0x0007U; diff --git a/game/client/gui/hotbar.cc b/game/client/gui/hotbar.cc index ca058a3..806d82b 100644 --- a/game/client/gui/hotbar.cc +++ b/game/client/gui/hotbar.cc @@ -1,183 +1,183 @@ -#include "client/pch.hh" - -#include "client/gui/hotbar.hh" - -#include "core/io/config_map.hh" - -#include "core/resource/resource.hh" - -#include "shared/world/item_registry.hh" - -#include "client/config/keybind.hh" - -#include "client/gui/settings.hh" -#include "client/gui/status_lines.hh" - -#include "client/io/glfw.hh" - -#include "client/resource/texture_gui.hh" - -#include "client/globals.hh" - -constexpr static float ITEM_SIZE = 20.0f; -constexpr static float ITEM_PADDING = 2.0f; -constexpr static float SELECTOR_PADDING = 1.0f; -constexpr static float HOTBAR_PADDING = 2.0f; - -unsigned int gui::hotbar::active_slot = 0U; -item_id gui::hotbar::slots[HOTBAR_SIZE]; - -static config::KeyBind hotbar_keys[HOTBAR_SIZE]; - -static resource_ptr hotbar_background; -static resource_ptr hotbar_selector; - -static ImU32 get_color_alpha(ImGuiCol style_color, float alpha) -{ - const auto& color = ImGui::GetStyleColorVec4(style_color); - return ImGui::GetColorU32(ImVec4(color.x, color.y, color.z, alpha)); -} - -static void update_hotbar_item(void) -{ - if(gui::hotbar::slots[gui::hotbar::active_slot] == NULL_ITEM_ID) { - gui::status_lines::unset(gui::STATUS_HOTBAR); - return; - } - - if(auto info = world::item_registry::find(gui::hotbar::slots[gui::hotbar::active_slot])) { - gui::status_lines::set(gui::STATUS_HOTBAR, info->name, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), 5.0f); - return; - } -} - -static void on_glfw_key(const io::GlfwKeyEvent& event) -{ - if((event.action == GLFW_PRESS) && !globals::gui_screen) { - for(unsigned int i = 0U; i < HOTBAR_SIZE; ++i) { - if(hotbar_keys[i].equals(event.key)) { - gui::hotbar::active_slot = i; - update_hotbar_item(); - break; - } - } - } -} - -static void on_glfw_scroll(const io::GlfwScrollEvent& event) -{ - if(!globals::gui_screen) { - if(event.dy < 0.0) { - gui::hotbar::next_slot(); - return; - } - - if(event.dy > 0.0) { - gui::hotbar::prev_slot(); - return; - } - } -} - -void gui::hotbar::init(void) -{ - hotbar_keys[0].set_key(GLFW_KEY_1); - hotbar_keys[1].set_key(GLFW_KEY_2); - hotbar_keys[2].set_key(GLFW_KEY_3); - hotbar_keys[3].set_key(GLFW_KEY_4); - hotbar_keys[4].set_key(GLFW_KEY_5); - hotbar_keys[5].set_key(GLFW_KEY_6); - hotbar_keys[6].set_key(GLFW_KEY_7); - hotbar_keys[7].set_key(GLFW_KEY_8); - hotbar_keys[8].set_key(GLFW_KEY_9); - - globals::client_config.add_value("hotbar.key.0", hotbar_keys[0]); - globals::client_config.add_value("hotbar.key.1", hotbar_keys[1]); - globals::client_config.add_value("hotbar.key.3", hotbar_keys[2]); - globals::client_config.add_value("hotbar.key.4", hotbar_keys[3]); - globals::client_config.add_value("hotbar.key.5", hotbar_keys[4]); - globals::client_config.add_value("hotbar.key.6", hotbar_keys[5]); - globals::client_config.add_value("hotbar.key.7", hotbar_keys[6]); - globals::client_config.add_value("hotbar.key.8", hotbar_keys[7]); - globals::client_config.add_value("hotbar.key.9", hotbar_keys[8]); - - settings::add_keybind(10, hotbar_keys[0], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.0"); - settings::add_keybind(11, hotbar_keys[1], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.1"); - settings::add_keybind(12, hotbar_keys[2], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.2"); - settings::add_keybind(13, hotbar_keys[3], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.3"); - settings::add_keybind(14, hotbar_keys[4], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.4"); - settings::add_keybind(15, hotbar_keys[5], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.5"); - settings::add_keybind(16, hotbar_keys[6], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.6"); - settings::add_keybind(17, hotbar_keys[7], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.7"); - settings::add_keybind(18, hotbar_keys[8], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.8"); - - hotbar_background = resource::load("textures/gui/hud_hotbar.png", TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); - hotbar_selector = resource::load("textures/gui/hud_selector.png", TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); - - globals::dispatcher.sink().connect<&on_glfw_key>(); - globals::dispatcher.sink().connect<&on_glfw_scroll>(); -} - -void gui::hotbar::shutdown(void) -{ - hotbar_background = nullptr; - hotbar_selector = nullptr; -} - -void gui::hotbar::layout(void) -{ - auto& style = ImGui::GetStyle(); - - auto item_size = ITEM_SIZE * globals::gui_scale; - auto hotbar_width = HOTBAR_SIZE * item_size; - auto hotbar_padding = HOTBAR_PADDING * globals::gui_scale; - - auto viewport = ImGui::GetMainViewport(); - auto draw_list = ImGui::GetForegroundDrawList(); - - // Draw the hotbar background image - auto background_start = ImVec2(0.5f * viewport->Size.x - 0.5f * hotbar_width, viewport->Size.y - item_size - hotbar_padding); - auto background_end = ImVec2(background_start.x + hotbar_width, background_start.y + item_size); - draw_list->AddImage(hotbar_background->handle, background_start, background_end); - - // Draw the hotbar selector image - auto selector_padding_a = SELECTOR_PADDING * globals::gui_scale; - auto selector_padding_b = SELECTOR_PADDING * globals::gui_scale * 2.0f; - auto selector_start = ImVec2( - background_start.x + gui::hotbar::active_slot * item_size - selector_padding_a, background_start.y - selector_padding_a); - auto selector_end = ImVec2(selector_start.x + item_size + selector_padding_b, selector_start.y + item_size + selector_padding_b); - draw_list->AddImage(hotbar_selector->handle, selector_start, selector_end); - - // Figure out item texture padding values - auto item_padding_a = ITEM_PADDING * globals::gui_scale; - auto item_padding_b = ITEM_PADDING * globals::gui_scale * 2.0f; - - // Draw individual item textures in the hotbar - for(std::size_t i = 0; i < HOTBAR_SIZE; ++i) { - const auto info = world::item_registry::find(gui::hotbar::slots[i]); - - if((info == nullptr) || (info->cached_texture == nullptr)) { - // There's either no item in the slot - // or the item doesn't have a texture - continue; - } - - const auto item_start = ImVec2(background_start.x + i * item_size + item_padding_a, background_start.y + item_padding_a); - const auto item_end = ImVec2(item_start.x + item_size - item_padding_b, item_start.y + item_size - item_padding_b); - draw_list->AddImage(info->cached_texture->handle, item_start, item_end); - } -} - -void gui::hotbar::next_slot(void) -{ - gui::hotbar::active_slot += 1U; - gui::hotbar::active_slot %= HOTBAR_SIZE; - update_hotbar_item(); -} - -void gui::hotbar::prev_slot(void) -{ - gui::hotbar::active_slot += HOTBAR_SIZE - 1U; - gui::hotbar::active_slot %= HOTBAR_SIZE; - update_hotbar_item(); -} +#include "client/pch.hh" + +#include "client/gui/hotbar.hh" + +#include "core/io/config_map.hh" + +#include "core/resource/resource.hh" + +#include "shared/world/item_registry.hh" + +#include "client/config/keybind.hh" + +#include "client/gui/settings.hh" +#include "client/gui/status_lines.hh" + +#include "client/io/glfw.hh" + +#include "client/resource/texture_gui.hh" + +#include "client/globals.hh" + +constexpr static float ITEM_SIZE = 20.0f; +constexpr static float ITEM_PADDING = 2.0f; +constexpr static float SELECTOR_PADDING = 1.0f; +constexpr static float HOTBAR_PADDING = 2.0f; + +unsigned int gui::hotbar::active_slot = 0U; +item_id gui::hotbar::slots[HOTBAR_SIZE]; + +static config::KeyBind hotbar_keys[HOTBAR_SIZE]; + +static resource_ptr hotbar_background; +static resource_ptr hotbar_selector; + +static ImU32 get_color_alpha(ImGuiCol style_color, float alpha) +{ + const auto& color = ImGui::GetStyleColorVec4(style_color); + return ImGui::GetColorU32(ImVec4(color.x, color.y, color.z, alpha)); +} + +static void update_hotbar_item(void) +{ + if(gui::hotbar::slots[gui::hotbar::active_slot] == NULL_ITEM_ID) { + gui::status_lines::unset(gui::STATUS_HOTBAR); + return; + } + + if(auto info = world::item_registry::find(gui::hotbar::slots[gui::hotbar::active_slot])) { + gui::status_lines::set(gui::STATUS_HOTBAR, info->name, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), 5.0f); + return; + } +} + +static void on_glfw_key(const io::GlfwKeyEvent& event) +{ + if((event.action == GLFW_PRESS) && !globals::gui_screen) { + for(unsigned int i = 0U; i < HOTBAR_SIZE; ++i) { + if(hotbar_keys[i].equals(event.key)) { + gui::hotbar::active_slot = i; + update_hotbar_item(); + break; + } + } + } +} + +static void on_glfw_scroll(const io::GlfwScrollEvent& event) +{ + if(!globals::gui_screen) { + if(event.dy < 0.0) { + gui::hotbar::next_slot(); + return; + } + + if(event.dy > 0.0) { + gui::hotbar::prev_slot(); + return; + } + } +} + +void gui::hotbar::init(void) +{ + hotbar_keys[0].set_key(GLFW_KEY_1); + hotbar_keys[1].set_key(GLFW_KEY_2); + hotbar_keys[2].set_key(GLFW_KEY_3); + hotbar_keys[3].set_key(GLFW_KEY_4); + hotbar_keys[4].set_key(GLFW_KEY_5); + hotbar_keys[5].set_key(GLFW_KEY_6); + hotbar_keys[6].set_key(GLFW_KEY_7); + hotbar_keys[7].set_key(GLFW_KEY_8); + hotbar_keys[8].set_key(GLFW_KEY_9); + + globals::client_config.add_value("hotbar.key.0", hotbar_keys[0]); + globals::client_config.add_value("hotbar.key.1", hotbar_keys[1]); + globals::client_config.add_value("hotbar.key.3", hotbar_keys[2]); + globals::client_config.add_value("hotbar.key.4", hotbar_keys[3]); + globals::client_config.add_value("hotbar.key.5", hotbar_keys[4]); + globals::client_config.add_value("hotbar.key.6", hotbar_keys[5]); + globals::client_config.add_value("hotbar.key.7", hotbar_keys[6]); + globals::client_config.add_value("hotbar.key.8", hotbar_keys[7]); + globals::client_config.add_value("hotbar.key.9", hotbar_keys[8]); + + settings::add_keybind(10, hotbar_keys[0], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.0"); + settings::add_keybind(11, hotbar_keys[1], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.1"); + settings::add_keybind(12, hotbar_keys[2], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.2"); + settings::add_keybind(13, hotbar_keys[3], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.3"); + settings::add_keybind(14, hotbar_keys[4], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.4"); + settings::add_keybind(15, hotbar_keys[5], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.5"); + settings::add_keybind(16, hotbar_keys[6], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.6"); + settings::add_keybind(17, hotbar_keys[7], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.7"); + settings::add_keybind(18, hotbar_keys[8], settings_location::KEYBOARD_GAMEPLAY, "hotbar.slot.8"); + + hotbar_background = resource::load("textures/gui/hud_hotbar.png", TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); + hotbar_selector = resource::load("textures/gui/hud_selector.png", TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); + + globals::dispatcher.sink().connect<&on_glfw_key>(); + globals::dispatcher.sink().connect<&on_glfw_scroll>(); +} + +void gui::hotbar::shutdown(void) +{ + hotbar_background = nullptr; + hotbar_selector = nullptr; +} + +void gui::hotbar::layout(void) +{ + auto& style = ImGui::GetStyle(); + + auto item_size = ITEM_SIZE * globals::gui_scale; + auto hotbar_width = HOTBAR_SIZE * item_size; + auto hotbar_padding = HOTBAR_PADDING * globals::gui_scale; + + auto viewport = ImGui::GetMainViewport(); + auto draw_list = ImGui::GetForegroundDrawList(); + + // Draw the hotbar background image + auto background_start = ImVec2(0.5f * viewport->Size.x - 0.5f * hotbar_width, viewport->Size.y - item_size - hotbar_padding); + auto background_end = ImVec2(background_start.x + hotbar_width, background_start.y + item_size); + draw_list->AddImage(hotbar_background->handle, background_start, background_end); + + // Draw the hotbar selector image + auto selector_padding_a = SELECTOR_PADDING * globals::gui_scale; + auto selector_padding_b = SELECTOR_PADDING * globals::gui_scale * 2.0f; + auto selector_start = ImVec2(background_start.x + gui::hotbar::active_slot * item_size - selector_padding_a, + background_start.y - selector_padding_a); + auto selector_end = ImVec2(selector_start.x + item_size + selector_padding_b, selector_start.y + item_size + selector_padding_b); + draw_list->AddImage(hotbar_selector->handle, selector_start, selector_end); + + // Figure out item texture padding values + auto item_padding_a = ITEM_PADDING * globals::gui_scale; + auto item_padding_b = ITEM_PADDING * globals::gui_scale * 2.0f; + + // Draw individual item textures in the hotbar + for(std::size_t i = 0; i < HOTBAR_SIZE; ++i) { + const auto info = world::item_registry::find(gui::hotbar::slots[i]); + + if((info == nullptr) || (info->cached_texture == nullptr)) { + // There's either no item in the slot + // or the item doesn't have a texture + continue; + } + + const auto item_start = ImVec2(background_start.x + i * item_size + item_padding_a, background_start.y + item_padding_a); + const auto item_end = ImVec2(item_start.x + item_size - item_padding_b, item_start.y + item_size - item_padding_b); + draw_list->AddImage(info->cached_texture->handle, item_start, item_end); + } +} + +void gui::hotbar::next_slot(void) +{ + gui::hotbar::active_slot += 1U; + gui::hotbar::active_slot %= HOTBAR_SIZE; + update_hotbar_item(); +} + +void gui::hotbar::prev_slot(void) +{ + gui::hotbar::active_slot += HOTBAR_SIZE - 1U; + gui::hotbar::active_slot %= HOTBAR_SIZE; + update_hotbar_item(); +} diff --git a/game/client/gui/hotbar.hh b/game/client/gui/hotbar.hh index 85d75aa..88ce791 100644 --- a/game/client/gui/hotbar.hh +++ b/game/client/gui/hotbar.hh @@ -1,27 +1,27 @@ -#pragma once - -#include "shared/types.hh" - -// TODO: design an inventory system and an item -// registry and integrate the hotbar into that system - -constexpr static unsigned int HOTBAR_SIZE = 9U; - -namespace gui::hotbar -{ -extern unsigned int active_slot; -extern item_id slots[HOTBAR_SIZE]; -} // namespace gui::hotbar - -namespace gui::hotbar -{ -void init(void); -void shutdown(void); -void layout(void); -} // namespace gui::hotbar - -namespace gui::hotbar -{ -void next_slot(void); -void prev_slot(void); -} // namespace gui::hotbar +#pragma once + +#include "shared/types.hh" + +// TODO: design an inventory system and an item +// registry and integrate the hotbar into that system + +constexpr static unsigned int HOTBAR_SIZE = 9U; + +namespace gui::hotbar +{ +extern unsigned int active_slot; +extern item_id slots[HOTBAR_SIZE]; +} // namespace gui::hotbar + +namespace gui::hotbar +{ +void init(void); +void shutdown(void); +void layout(void); +} // namespace gui::hotbar + +namespace gui::hotbar +{ +void next_slot(void); +void prev_slot(void); +} // namespace gui::hotbar diff --git a/game/client/gui/imdraw_ext.cc b/game/client/gui/imdraw_ext.cc index 832f284..c3d40c9 100644 --- a/game/client/gui/imdraw_ext.cc +++ b/game/client/gui/imdraw_ext.cc @@ -1,34 +1,34 @@ -#include "client/pch.hh" - -#include "client/gui/imdraw_ext.hh" - -#include "client/globals.hh" - -void gui::imdraw_ext::text_shadow( - const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, ImDrawList* draw_list) -{ - imdraw_ext::text_shadow(text, position, text_color, shadow_color, font, draw_list, font->LegacySize); -} - -void gui::imdraw_ext::text_shadow(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, - ImDrawList* draw_list, float font_size) -{ - const auto shadow_position = ImVec2(position.x + 0.5f * globals::gui_scale, position.y + 0.5f * globals::gui_scale); - draw_list->AddText(font, globals::gui_scale * font_size, shadow_position, shadow_color, text.c_str(), text.c_str() + text.size()); - draw_list->AddText(font, globals::gui_scale * font_size, position, text_color, text.c_str(), text.c_str() + text.size()); -} - -void gui::imdraw_ext::text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, - ImDrawList* draw_list, float wrap_width) -{ - imdraw_ext::text_shadow_w(text, position, text_color, shadow_color, font, draw_list, font->LegacySize, wrap_width); -} - -void gui::imdraw_ext::text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, - ImDrawList* draw_list, float font_size, float wrap_width) -{ - const auto shadow_position = ImVec2(position.x + 0.5f * globals::gui_scale, position.y + 0.5f * globals::gui_scale); - draw_list->AddText( - font, globals::gui_scale * font_size, shadow_position, shadow_color, text.c_str(), text.c_str() + text.size(), wrap_width); - draw_list->AddText(font, globals::gui_scale * font_size, position, text_color, text.c_str(), text.c_str() + text.size(), wrap_width); -} +#include "client/pch.hh" + +#include "client/gui/imdraw_ext.hh" + +#include "client/globals.hh" + +void gui::imdraw_ext::text_shadow(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, + ImDrawList* draw_list) +{ + imdraw_ext::text_shadow(text, position, text_color, shadow_color, font, draw_list, font->LegacySize); +} + +void gui::imdraw_ext::text_shadow(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, + ImDrawList* draw_list, float font_size) +{ + const auto shadow_position = ImVec2(position.x + 0.5f * globals::gui_scale, position.y + 0.5f * globals::gui_scale); + draw_list->AddText(font, globals::gui_scale * font_size, shadow_position, shadow_color, text.c_str(), text.c_str() + text.size()); + draw_list->AddText(font, globals::gui_scale * font_size, position, text_color, text.c_str(), text.c_str() + text.size()); +} + +void gui::imdraw_ext::text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, + ImDrawList* draw_list, float wrap_width) +{ + imdraw_ext::text_shadow_w(text, position, text_color, shadow_color, font, draw_list, font->LegacySize, wrap_width); +} + +void gui::imdraw_ext::text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, + ImDrawList* draw_list, float font_size, float wrap_width) +{ + const auto shadow_position = ImVec2(position.x + 0.5f * globals::gui_scale, position.y + 0.5f * globals::gui_scale); + draw_list->AddText(font, globals::gui_scale * font_size, shadow_position, shadow_color, text.c_str(), text.c_str() + text.size(), + wrap_width); + draw_list->AddText(font, globals::gui_scale * font_size, position, text_color, text.c_str(), text.c_str() + text.size(), wrap_width); +} diff --git a/game/client/gui/imdraw_ext.hh b/game/client/gui/imdraw_ext.hh index a7e1503..e1475b2 100644 --- a/game/client/gui/imdraw_ext.hh +++ b/game/client/gui/imdraw_ext.hh @@ -1,17 +1,17 @@ -#pragma once - -namespace gui::imdraw_ext -{ -void text_shadow(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, - ImDrawList* draw_list); -void text_shadow(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, ImDrawList* draw_list, - float font_size); -} // namespace gui::imdraw_ext - -namespace gui::imdraw_ext -{ -void text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, - ImDrawList* draw_list, float wrap_width); -void text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, - ImDrawList* draw_list, float font_size, float wrap_width); -} // namespace gui::imdraw_ext +#pragma once + +namespace gui::imdraw_ext +{ +void text_shadow(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, + ImDrawList* draw_list); +void text_shadow(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, ImDrawList* draw_list, + float font_size); +} // namespace gui::imdraw_ext + +namespace gui::imdraw_ext +{ +void text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, + ImDrawList* draw_list, float wrap_width); +void text_shadow_w(const std::string& text, const ImVec2& position, ImU32 text_color, ImU32 shadow_color, ImFont* font, + ImDrawList* draw_list, float font_size, float wrap_width); +} // namespace gui::imdraw_ext diff --git a/game/client/gui/language.cc b/game/client/gui/language.cc index f63dd99..57a43fe 100644 --- a/game/client/gui/language.cc +++ b/game/client/gui/language.cc @@ -1,201 +1,201 @@ -#include "client/pch.hh" - -#include "client/gui/language.hh" - -#include "core/config/string.hh" - -#include "core/io/config_map.hh" - -#include "client/gui/settings.hh" - -#include "client/globals.hh" - -constexpr static std::string_view DEFAULT_LANGUAGE = "en_US"; - -// Available languages are kept in a special manifest file which -// is essentially a key-value map of semi-IETF-compliant language tags -// and the language's endonym; after reading the manifest, the translation -// system knows what language it can load and will act accordingly -constexpr static std::string_view MANIFEST_PATH = "lang/manifest.json"; - -static gui::LanguageManifest manifest; -static gui::LanguageIterator current_language; -static std::unordered_map language_map; -static std::unordered_map ietf_map; -static config::String config_language(DEFAULT_LANGUAGE); - -static void send_language_event(gui::LanguageIterator new_language) -{ - gui::LanguageSetEvent event; - event.new_language = new_language; - globals::dispatcher.trigger(event); -} - -void gui::language::init(void) -{ - globals::client_config.add_value("language", config_language); - - settings::add_language_select(0, settings_location::GENERAL, "language"); - - auto file = PHYSFS_openRead(std::string(MANIFEST_PATH).c_str()); - - if(file == nullptr) { - spdlog::critical("language: {}: {}", MANIFEST_PATH, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); - std::terminate(); - } - - auto source = std::string(PHYSFS_fileLength(file), char(0x00)); - PHYSFS_readBytes(file, source.data(), source.size()); - PHYSFS_close(file); - - auto jsonv = json_parse_string(source.c_str()); - const auto json = json_value_get_object(jsonv); - const auto count = json_object_get_count(json); - - if((jsonv == nullptr) || (json == nullptr) || (count == 0)) { - spdlog::critical("language: {}: parse error", MANIFEST_PATH); - json_value_free(jsonv); - std::terminate(); - } - - for(std::size_t i = 0; i < count; ++i) { - const auto ietf = json_object_get_name(json, i); - const auto value = json_object_get_value_at(json, i); - const auto endonym = json_value_get_string(value); - - if(ietf && endonym) { - LanguageInfo info; - info.ietf = std::string(ietf); - info.endonym = std::string(endonym); - info.display = std::format("{} ({})", endonym, ietf); - manifest.push_back(info); - } - } - - for(auto it = manifest.cbegin(); it != manifest.cend(); ++it) { - ietf_map.emplace(it->ietf, it); - } - - json_value_free(jsonv); - - // This is temporary! This value will - // be overriden in init_late after the - // config system updates config_language - current_language = manifest.cend(); -} - -void gui::language::init_late(void) -{ - auto user_language = ietf_map.find(config_language.get_value()); - - if(user_language != ietf_map.cend()) { - gui::language::set(user_language->second); - return; - } - - auto fallback = ietf_map.find(std::string(DEFAULT_LANGUAGE)); - - if(fallback != ietf_map.cend()) { - gui::language::set(fallback->second); - return; - } - - spdlog::critical("language: we're doomed!"); - spdlog::critical("language: {} doesn't exist!", DEFAULT_LANGUAGE); - std::terminate(); -} - -void gui::language::set(LanguageIterator new_language) -{ - if(new_language != manifest.cend()) { - auto path = std::format("lang/lang.{}.json", new_language->ietf); - - auto file = PHYSFS_openRead(path.c_str()); - - if(file == nullptr) { - spdlog::warn("language: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); - send_language_event(new_language); - return; - } - - auto source = std::string(PHYSFS_fileLength(file), char(0x00)); - PHYSFS_readBytes(file, source.data(), source.size()); - PHYSFS_close(file); - - auto jsonv = json_parse_string(source.c_str()); - const auto json = json_value_get_object(jsonv); - const auto count = json_object_get_count(json); - - if((jsonv == nullptr) || (json == nullptr) || (count == 0)) { - spdlog::warn("language: {}: parse error", path); - send_language_event(new_language); - json_value_free(jsonv); - return; - } - - language_map.clear(); - - for(size_t i = 0; i < count; ++i) { - const auto key = json_object_get_name(json, i); - const auto value = json_object_get_value_at(json, i); - const auto value_str = json_value_get_string(value); - - if(key && value_str) { - language_map.emplace(key, value_str); - continue; - } - } - - json_value_free(jsonv); - - current_language = new_language; - config_language.set(new_language->ietf.c_str()); - } - - send_language_event(new_language); -} - -gui::LanguageIterator gui::language::get_current(void) -{ - return current_language; -} - -gui::LanguageIterator gui::language::find(std::string_view ietf) -{ - const auto it = ietf_map.find(std::string(ietf)); - if(it != ietf_map.cend()) { - return it->second; - } - else { - return manifest.cend(); - } -} - -gui::LanguageIterator gui::language::cbegin(void) -{ - return manifest.cbegin(); -} - -gui::LanguageIterator gui::language::cend(void) -{ - return manifest.cend(); -} - -std::string_view gui::language::resolve(std::string_view key) -{ - const auto it = language_map.find(std::string(key)); - - if(it != language_map.cend()) { - return it->second; - } - - return key; -} - -std::string gui::language::resolve_gui(std::string_view key) -{ - // We need window tags to retain their hierarchy when a language - // dynamically changes; ImGui allows to provide hidden unique identifiers - // to GUI primitives that have their name change dynamically, so we're using this - return std::format("{}###{}", gui::language::resolve(key), key); -} +#include "client/pch.hh" + +#include "client/gui/language.hh" + +#include "core/config/string.hh" + +#include "core/io/config_map.hh" + +#include "client/gui/settings.hh" + +#include "client/globals.hh" + +constexpr static std::string_view DEFAULT_LANGUAGE = "en_US"; + +// Available languages are kept in a special manifest file which +// is essentially a key-value map of semi-IETF-compliant language tags +// and the language's endonym; after reading the manifest, the translation +// system knows what language it can load and will act accordingly +constexpr static std::string_view MANIFEST_PATH = "lang/manifest.json"; + +static gui::LanguageManifest manifest; +static gui::LanguageIterator current_language; +static std::unordered_map language_map; +static std::unordered_map ietf_map; +static config::String config_language(DEFAULT_LANGUAGE); + +static void send_language_event(gui::LanguageIterator new_language) +{ + gui::LanguageSetEvent event; + event.new_language = new_language; + globals::dispatcher.trigger(event); +} + +void gui::language::init(void) +{ + globals::client_config.add_value("language", config_language); + + settings::add_language_select(0, settings_location::GENERAL, "language"); + + auto file = PHYSFS_openRead(std::string(MANIFEST_PATH).c_str()); + + if(file == nullptr) { + spdlog::critical("language: {}: {}", MANIFEST_PATH, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); + std::terminate(); + } + + auto source = std::string(PHYSFS_fileLength(file), char(0x00)); + PHYSFS_readBytes(file, source.data(), source.size()); + PHYSFS_close(file); + + auto jsonv = json_parse_string(source.c_str()); + const auto json = json_value_get_object(jsonv); + const auto count = json_object_get_count(json); + + if((jsonv == nullptr) || (json == nullptr) || (count == 0)) { + spdlog::critical("language: {}: parse error", MANIFEST_PATH); + json_value_free(jsonv); + std::terminate(); + } + + for(std::size_t i = 0; i < count; ++i) { + const auto ietf = json_object_get_name(json, i); + const auto value = json_object_get_value_at(json, i); + const auto endonym = json_value_get_string(value); + + if(ietf && endonym) { + LanguageInfo info; + info.ietf = std::string(ietf); + info.endonym = std::string(endonym); + info.display = std::format("{} ({})", endonym, ietf); + manifest.push_back(info); + } + } + + for(auto it = manifest.cbegin(); it != manifest.cend(); ++it) { + ietf_map.emplace(it->ietf, it); + } + + json_value_free(jsonv); + + // This is temporary! This value will + // be overriden in init_late after the + // config system updates config_language + current_language = manifest.cend(); +} + +void gui::language::init_late(void) +{ + auto user_language = ietf_map.find(config_language.get_value()); + + if(user_language != ietf_map.cend()) { + gui::language::set(user_language->second); + return; + } + + auto fallback = ietf_map.find(std::string(DEFAULT_LANGUAGE)); + + if(fallback != ietf_map.cend()) { + gui::language::set(fallback->second); + return; + } + + spdlog::critical("language: we're doomed!"); + spdlog::critical("language: {} doesn't exist!", DEFAULT_LANGUAGE); + std::terminate(); +} + +void gui::language::set(LanguageIterator new_language) +{ + if(new_language != manifest.cend()) { + auto path = std::format("lang/lang.{}.json", new_language->ietf); + + auto file = PHYSFS_openRead(path.c_str()); + + if(file == nullptr) { + spdlog::warn("language: {}: {}", path, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())); + send_language_event(new_language); + return; + } + + auto source = std::string(PHYSFS_fileLength(file), char(0x00)); + PHYSFS_readBytes(file, source.data(), source.size()); + PHYSFS_close(file); + + auto jsonv = json_parse_string(source.c_str()); + const auto json = json_value_get_object(jsonv); + const auto count = json_object_get_count(json); + + if((jsonv == nullptr) || (json == nullptr) || (count == 0)) { + spdlog::warn("language: {}: parse error", path); + send_language_event(new_language); + json_value_free(jsonv); + return; + } + + language_map.clear(); + + for(size_t i = 0; i < count; ++i) { + const auto key = json_object_get_name(json, i); + const auto value = json_object_get_value_at(json, i); + const auto value_str = json_value_get_string(value); + + if(key && value_str) { + language_map.emplace(key, value_str); + continue; + } + } + + json_value_free(jsonv); + + current_language = new_language; + config_language.set(new_language->ietf.c_str()); + } + + send_language_event(new_language); +} + +gui::LanguageIterator gui::language::get_current(void) +{ + return current_language; +} + +gui::LanguageIterator gui::language::find(std::string_view ietf) +{ + const auto it = ietf_map.find(std::string(ietf)); + if(it != ietf_map.cend()) { + return it->second; + } + else { + return manifest.cend(); + } +} + +gui::LanguageIterator gui::language::cbegin(void) +{ + return manifest.cbegin(); +} + +gui::LanguageIterator gui::language::cend(void) +{ + return manifest.cend(); +} + +std::string_view gui::language::resolve(std::string_view key) +{ + const auto it = language_map.find(std::string(key)); + + if(it != language_map.cend()) { + return it->second; + } + + return key; +} + +std::string gui::language::resolve_gui(std::string_view key) +{ + // We need window tags to retain their hierarchy when a language + // dynamically changes; ImGui allows to provide hidden unique identifiers + // to GUI primitives that have their name change dynamically, so we're using this + return std::format("{}###{}", gui::language::resolve(key), key); +} diff --git a/game/client/gui/language.hh b/game/client/gui/language.hh index 90132d7..0628941 100644 --- a/game/client/gui/language.hh +++ b/game/client/gui/language.hh @@ -1,42 +1,42 @@ -#pragma once - -namespace gui -{ -struct LanguageInfo final { - std::string endonym; // Language's self-name - std::string display; // Display for the settings GUI - std::string ietf; // Semi-compliant language abbreviation -}; - -using LanguageManifest = std::vector; -using LanguageIterator = LanguageManifest::const_iterator; - -struct LanguageSetEvent final { - LanguageIterator new_language; -}; -} // namespace gui - -namespace gui::language -{ -void init(void); -void init_late(void); -} // namespace gui::language - -namespace gui::language -{ -void set(LanguageIterator new_language); -} // namespace gui::language - -namespace gui::language -{ -LanguageIterator get_current(void); -LanguageIterator find(std::string_view ietf); -LanguageIterator cbegin(void); -LanguageIterator cend(void); -} // namespace gui::language - -namespace gui::language -{ -std::string_view resolve(std::string_view key); -std::string resolve_gui(std::string_view key); -} // namespace gui::language +#pragma once + +namespace gui +{ +struct LanguageInfo final { + std::string endonym; // Language's self-name + std::string display; // Display for the settings GUI + std::string ietf; // Semi-compliant language abbreviation +}; + +using LanguageManifest = std::vector; +using LanguageIterator = LanguageManifest::const_iterator; + +struct LanguageSetEvent final { + LanguageIterator new_language; +}; +} // namespace gui + +namespace gui::language +{ +void init(void); +void init_late(void); +} // namespace gui::language + +namespace gui::language +{ +void set(LanguageIterator new_language); +} // namespace gui::language + +namespace gui::language +{ +LanguageIterator get_current(void); +LanguageIterator find(std::string_view ietf); +LanguageIterator cbegin(void); +LanguageIterator cend(void); +} // namespace gui::language + +namespace gui::language +{ +std::string_view resolve(std::string_view key); +std::string resolve_gui(std::string_view key); +} // namespace gui::language diff --git a/game/client/gui/main_menu.cc b/game/client/gui/main_menu.cc index 3c68612..aa506d3 100644 --- a/game/client/gui/main_menu.cc +++ b/game/client/gui/main_menu.cc @@ -1,172 +1,172 @@ -#include "client/pch.hh" - -#include "client/gui/main_menu.hh" - -#include "core/math/constexpr.hh" - -#include "core/resource/resource.hh" - -#include "core/version.hh" - -#include "client/gui/gui_screen.hh" -#include "client/gui/language.hh" -#include "client/gui/window_title.hh" - -#include "client/io/glfw.hh" - -#include "client/resource/texture_gui.hh" - -#include "client/globals.hh" -#include "client/session.hh" - -constexpr static ImGuiWindowFlags WINDOW_FLAGS = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration; - -static std::string str_play; -static std::string str_resume; -static std::string str_settings; -static std::string str_leave; -static std::string str_quit; - -static resource_ptr title; -static float title_aspect; - -static void on_glfw_key(const io::GlfwKeyEvent& event) -{ - if(session::is_ingame() && (event.key == GLFW_KEY_ESCAPE) && (event.action == GLFW_PRESS)) { - if(globals::gui_screen == GUI_SCREEN_NONE) { - globals::gui_screen = GUI_MAIN_MENU; - return; - } - - if(globals::gui_screen == GUI_MAIN_MENU) { - globals::gui_screen = GUI_SCREEN_NONE; - return; - } - } -} - -static void on_language_set(const gui::LanguageSetEvent& event) -{ - str_play = gui::language::resolve_gui("main_menu.play"); - str_resume = gui::language::resolve_gui("main_menu.resume"); - str_settings = gui::language::resolve("main_menu.settings"); - str_leave = gui::language::resolve("main_menu.leave"); - str_quit = gui::language::resolve("main_menu.quit"); -} - -void gui::main_menu::init(void) -{ - title = resource::load("textures/gui/menu_title.png", TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); - - if(title == nullptr) { - spdlog::critical("main_menu: texture load failed"); - std::terminate(); - } - - if(title->size.x > title->size.y) { - title_aspect = static_cast(title->size.x) / static_cast(title->size.y); - } - else { - title_aspect = static_cast(title->size.y) / static_cast(title->size.x); - } - - globals::dispatcher.sink().connect<&on_glfw_key>(); - globals::dispatcher.sink().connect<&on_language_set>(); -} - -void gui::main_menu::shutdown(void) -{ - title = nullptr; -} - -void gui::main_menu::layout(void) -{ - const auto viewport = ImGui::GetMainViewport(); - const auto window_start = ImVec2(0.0f, viewport->Size.y * 0.15f); - const auto window_size = ImVec2(viewport->Size.x, viewport->Size.y); - - ImGui::SetNextWindowPos(window_start); - ImGui::SetNextWindowSize(window_size); - - if(ImGui::Begin("###main_menu", nullptr, WINDOW_FLAGS)) { - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 2.0f * globals::gui_scale)); - - if(session::is_ingame()) { - ImGui::Dummy(ImVec2(0.0f, 32.0f * globals::gui_scale)); - } - else { - auto reference_height = 0.225f * window_size.y; - auto image_width = math::min(window_size.x, reference_height * title_aspect); - auto image_height = image_width / title_aspect; - ImGui::SetCursorPosX(0.5f * (window_size.x - image_width)); - ImGui::Image(title->handle, ImVec2(image_width, image_height)); - } - - ImGui::Dummy(ImVec2(0.0f, 24.0f * globals::gui_scale)); - - const float button_width = 240.0f * globals::gui_scale; - const float button_xpos = 0.5f * (window_size.x - button_width); - - if(session::is_ingame()) { - ImGui::SetCursorPosX(button_xpos); - - if(ImGui::Button(str_resume.c_str(), ImVec2(button_width, 0.0f))) { - globals::gui_screen = GUI_SCREEN_NONE; - } - - ImGui::Spacing(); - } - else { - ImGui::SetCursorPosX(button_xpos); - - if(ImGui::Button(str_play.c_str(), ImVec2(button_width, 0.0f))) { - globals::gui_screen = GUI_PLAY_MENU; - } - - ImGui::Spacing(); - } - - ImGui::SetCursorPosX(button_xpos); - - if(ImGui::Button(str_settings.c_str(), ImVec2(button_width, 0.0f))) { - globals::gui_screen = GUI_SETTINGS; - } - - ImGui::Spacing(); - - if(session::is_ingame()) { - ImGui::SetCursorPosX(button_xpos); - - if(ImGui::Button(str_leave.c_str(), ImVec2(button_width, 0.0f))) { - session::disconnect("protocol.client_disconnect"); - globals::gui_screen = GUI_PLAY_MENU; - gui::window_title::update(); - } - - ImGui::Spacing(); - } - else { - ImGui::SetCursorPosX(button_xpos); - - if(ImGui::Button(str_quit.c_str(), ImVec2(button_width, 0.0f))) { - glfwSetWindowShouldClose(globals::window, true); - } - - ImGui::Spacing(); - } - - if(!session::is_ingame()) { - const auto& padding = ImGui::GetStyle().FramePadding; - const auto& spacing = ImGui::GetStyle().ItemSpacing; - - ImGui::PushFont(globals::font_unscii8, 4.0f); - ImGui::SetCursorScreenPos(ImVec2(padding.x + spacing.x, window_size.y - ImGui::GetFontSize() - padding.y - spacing.y)); - ImGui::Text("Voxelius %*s", version::semver.size(), version::semver.data()); // string_view is not always null-terminated - ImGui::PopFont(); - } - - ImGui::PopStyleVar(); - } - - ImGui::End(); -} +#include "client/pch.hh" + +#include "client/gui/main_menu.hh" + +#include "core/math/constexpr.hh" + +#include "core/resource/resource.hh" + +#include "core/version.hh" + +#include "client/gui/gui_screen.hh" +#include "client/gui/language.hh" +#include "client/gui/window_title.hh" + +#include "client/io/glfw.hh" + +#include "client/resource/texture_gui.hh" + +#include "client/globals.hh" +#include "client/session.hh" + +constexpr static ImGuiWindowFlags WINDOW_FLAGS = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration; + +static std::string str_play; +static std::string str_resume; +static std::string str_settings; +static std::string str_leave; +static std::string str_quit; + +static resource_ptr title; +static float title_aspect; + +static void on_glfw_key(const io::GlfwKeyEvent& event) +{ + if(session::is_ingame() && (event.key == GLFW_KEY_ESCAPE) && (event.action == GLFW_PRESS)) { + if(globals::gui_screen == GUI_SCREEN_NONE) { + globals::gui_screen = GUI_MAIN_MENU; + return; + } + + if(globals::gui_screen == GUI_MAIN_MENU) { + globals::gui_screen = GUI_SCREEN_NONE; + return; + } + } +} + +static void on_language_set(const gui::LanguageSetEvent& event) +{ + str_play = gui::language::resolve_gui("main_menu.play"); + str_resume = gui::language::resolve_gui("main_menu.resume"); + str_settings = gui::language::resolve("main_menu.settings"); + str_leave = gui::language::resolve("main_menu.leave"); + str_quit = gui::language::resolve("main_menu.quit"); +} + +void gui::main_menu::init(void) +{ + title = resource::load("textures/gui/menu_title.png", TEXTURE_GUI_LOAD_CLAMP_S | TEXTURE_GUI_LOAD_CLAMP_T); + + if(title == nullptr) { + spdlog::critical("main_menu: texture load failed"); + std::terminate(); + } + + if(title->size.x > title->size.y) { + title_aspect = static_cast(title->size.x) / static_cast(title->size.y); + } + else { + title_aspect = static_cast(title->size.y) / static_cast(title->size.x); + } + + globals::dispatcher.sink().connect<&on_glfw_key>(); + globals::dispatcher.sink().connect<&on_language_set>(); +} + +void gui::main_menu::shutdown(void) +{ + title = nullptr; +} + +void gui::main_menu::layout(void) +{ + const auto viewport = ImGui::GetMainViewport(); + const auto window_start = ImVec2(0.0f, viewport->Size.y * 0.15f); + const auto window_size = ImVec2(viewport->Size.x, viewport->Size.y); + + ImGui::SetNextWindowPos(window_start); + ImGui::SetNextWindowSize(window_size); + + if(ImGui::Begin("###main_menu", nullptr, WINDOW_FLAGS)) { + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 2.0f * globals::gui_scale)); + + if(session::is_ingame()) { + ImGui::Dummy(ImVec2(0.0f, 32.0f * globals::gui_scale)); + } + else { + auto reference_height = 0.225f * window_size.y; + auto image_width = math::min(window_size.x, reference_height * title_aspect); + auto image_height = image_width / title_aspect; + ImGui::SetCursorPosX(0.5f * (window_size.x - image_width)); + ImGui::Image(title->handle, ImVec2(image_width, image_height)); + } + + ImGui::Dummy(ImVec2(0.0f, 24.0f * globals::gui_scale)); + + const float button_width = 240.0f * globals::gui_scale; + const float button_xpos = 0.5f * (window_size.x - button_width); + + if(session::is_ingame()) { + ImGui::SetCursorPosX(button_xpos); + + if(ImGui::Button(str_resume.c_str(), ImVec2(button_width, 0.0f))) { + globals::gui_screen = GUI_SCREEN_NONE; + } + + ImGui::Spacing(); + } + else { + ImGui::SetCursorPosX(button_xpos); + + if(ImGui::Button(str_play.c_str(), ImVec2(button_width, 0.0f))) { + globals::gui_screen = GUI_PLAY_MENU; + } + + ImGui::Spacing(); + } + + ImGui::SetCursorPosX(button_xpos); + + if(ImGui::Button(str_settings.c_str(), ImVec2(button_width, 0.0f))) { + globals::gui_screen = GUI_SETTINGS; + } + + ImGui::Spacing(); + + if(session::is_ingame()) { + ImGui::SetCursorPosX(button_xpos); + + if(ImGui::Button(str_leave.c_str(), ImVec2(button_width, 0.0f))) { + session::disconnect("protocol.client_disconnect"); + globals::gui_screen = GUI_PLAY_MENU; + gui::window_title::update(); + } + + ImGui::Spacing(); + } + else { + ImGui::SetCursorPosX(button_xpos); + + if(ImGui::Button(str_quit.c_str(), ImVec2(button_width, 0.0f))) { + glfwSetWindowShouldClose(globals::window, true); + } + + ImGui::Spacing(); + } + + if(!session::is_ingame()) { + const auto& padding = ImGui::GetStyle().FramePadding; + const auto& spacing = ImGui::GetStyle().ItemSpacing; + + ImGui::PushFont(globals::font_unscii8, 4.0f); + ImGui::SetCursorScreenPos(ImVec2(padding.x + spacing.x, window_size.y - ImGui::GetFontSize() - padding.y - spacing.y)); + ImGui::Text("Voxelius %*s", version::semver.size(), version::semver.data()); // string_view is not always null-terminated + ImGui::PopFont(); + } + + ImGui::PopStyleVar(); + } + + ImGui::End(); +} diff --git a/game/client/gui/main_menu.hh b/game/client/gui/main_menu.hh index 205f078..8e30e38 100644 --- a/game/client/gui/main_menu.hh +++ b/game/client/gui/main_menu.hh @@ -1,8 +1,8 @@ -#pragma once - -namespace gui::main_menu -{ -void init(void); -void shutdown(void); -void layout(void); -} // namespace gui::main_menu +#pragma once + +namespace gui::main_menu +{ +void init(void); +void shutdown(void); +void layout(void); +} // namespace gui::main_menu diff --git a/game/client/gui/message_box.cc b/game/client/gui/message_box.cc index 59e2d33..b7f109a 100644 --- a/game/client/gui/message_box.cc +++ b/game/client/gui/message_box.cc @@ -1,95 +1,95 @@ -#include "client/pch.hh" - -#include "client/gui/message_box.hh" - -#include "client/gui/gui_screen.hh" -#include "client/gui/language.hh" - -#include "client/globals.hh" - -constexpr static ImGuiWindowFlags WINDOW_FLAGS = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoDecoration; - -struct Button final { - gui::message_box_action action; - std::string str_title; -}; - -static std::string str_title; -static std::string str_subtitle; -static std::vector