diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..f63b55e --- /dev/null +++ b/.clang-format @@ -0,0 +1,321 @@ +--- +Language: Cpp +AlignAfterOpenBracket: true +AccessModifierOffset: -4 +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: true + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + AlignPPAndNotPP: true + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowBreakBeforeQtProperty: false +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AllowShortNamespacesOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AttributeMacros: + - __capability +BinPackArguments: true +BinPackLongBracedList: true +BinPackParameters: BinPack +BitFieldColonSpacing: Both +BracedInitializerIndentWidth: -1 +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterOpenBracketBracedList: false +BreakAfterOpenBracketFunction: false +BreakAfterOpenBracketIf: false +BreakAfterOpenBracketLoop: false +BreakAfterOpenBracketSwitch: false +BreakAfterReturnType: None +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeCloseBracketBracedList: false +BreakBeforeCloseBracketFunction: false +BreakBeforeCloseBracketIf: false +BreakBeforeCloseBracketLoop: false +BreakBeforeCloseBracketSwitch: false +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTemplateCloser: false +BreakBeforeTernaryOperators: true +BreakBinaryOperations: Never +BreakConstructorInitializers: BeforeColon +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +BreakTemplateDeclarations: MultiLine +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: AlignFirstComment +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +EnumTrailingComma: Leave +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExportBlock: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigitsInsert: 0 + BinaryMaxDigitsRemove: 0 + Decimal: 0 + DecimalMinDigitsInsert: 0 + DecimalMaxDigitsRemove: 0 + Hex: 0 + HexMinDigitsInsert: 0 + HexMaxDigitsRemove: 0 + BinaryMinDigits: 0 + DecimalMinDigits: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: true + AtStartOfFile: true +KeepFormFeed: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MainIncludeChar: Quote +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +NumericLiteralCase: + ExponentLetter: Leave + HexDigit: Leave + Prefix: Leave + Suffix: Leave +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +OneLineFormatOffRegex: '' +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakBeforeMemberAccess: 150 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: Always +RemoveBracesLLVM: false +RemoveEmptyLinesInUnwrappedLines: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: + Enabled: true + IgnoreCase: false + IgnoreExtension: false +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterOperatorKeyword: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterNot: false + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBraces: Never +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TableGenBreakInsideDAGArg: DontBreak +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +WrapNamespaceBodyWithEmptyLines: Leave +... + diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 0000000..80784e6 --- /dev/null +++ b/.clang-format-ignore @@ -0,0 +1,3 @@ +third_party/ +build/ +vendor/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..84e87a3 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,8 @@ +repos: + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: "v22.1.4" + hooks: + - id: clang-format + args: ["--style=file"] + types_or: ["c++", "c"] + exclude: '^third_party/.*$' diff --git a/include/Cubed/AABB.hpp b/include/Cubed/AABB.hpp index 99aa883..ec6ad52 100644 --- a/include/Cubed/AABB.hpp +++ b/include/Cubed/AABB.hpp @@ -3,17 +3,12 @@ namespace Cubed { - struct AABB { glm::vec3 min{0.0f, 0.0f, 0.0f}; glm::vec3 max{0.0f, 0.0f, 0.0f}; - AABB(glm::vec3 min_point, glm::vec3 max_point): - min(min_point), - max(max_point) - { - - } + AABB(glm::vec3 min_point, glm::vec3 max_point) + : min(min_point), max(max_point) {} bool intersects(const AABB& other) const { return (min.x <= other.max.x && max.x >= other.min.x) && @@ -22,4 +17,4 @@ struct AABB { } }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/app.hpp b/include/Cubed/app.hpp index 45f702f..516b74d 100644 --- a/include/Cubed/app.hpp +++ b/include/Cubed/app.hpp @@ -1,28 +1,32 @@ #pragma once - -#include -#include -#include -#include -#include -#include -#include +#define GLFW_INCLUDE_NONE +#include "Cubed/camera.hpp" +#include "Cubed/dev_panel.hpp" +#include "Cubed/gameplay/world.hpp" +#include "Cubed/renderer.hpp" +#include "Cubed/texture_manager.hpp" +#include "Cubed/window.hpp" namespace Cubed { class App { public: App(); ~App(); - static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos); - static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); - static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); + static void cursor_position_callback(GLFWwindow* window, double xpos, + double ypos); + static void key_callback(GLFWwindow* window, int key, int scancode, + int action, int mods); + static void mouse_button_callback(GLFWwindow* window, int button, + int action, int mods); static void window_focus_callback(GLFWwindow* window, int focused); - static void window_reshape_callback(GLFWwindow* window, int new_width, int new_height); - static void mouse_scroll_callback(GLFWwindow* window, double xoffset, double yoffset); + static void window_reshape_callback(GLFWwindow* window, int new_width, + int new_height); + static void mouse_scroll_callback(GLFWwindow* window, double xoffset, + double yoffset); static void cursor_enter_callback(GLFWwindow* window, int entered); static void char_callback(GLFWwindow* window, unsigned int ch); static int start_cubed_application(int argc, char** argv); - + static unsigned int seed(); static float delte_time(); static float get_fps(); @@ -34,7 +38,6 @@ public: Window& window(); World& world(); - private: Camera m_camera; TextureManager m_texture_manager; @@ -43,23 +46,23 @@ private: Renderer m_renderer{m_camera, m_world, m_texture_manager, m_dev_panel}; Window m_window{m_renderer}; - + inline static double last_time = glfwGetTime(); inline static double current_time = glfwGetTime(); inline static double delta_time = 0.0f; inline static double fps_time_count = 0.0f; inline static int frame_count = 0; inline static int fps = 0; - + void init(); - + auto init_camera(); auto init_texture(); auto init_world(); - + void render(); void run(); void update(); }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/camera.hpp b/include/Cubed/camera.hpp index 5676ea4..8354016 100644 --- a/include/Cubed/camera.hpp +++ b/include/Cubed/camera.hpp @@ -1,27 +1,23 @@ #pragma once +#define GLFW_INCLUDE_NONE +#include #include #include #include -#include -#include namespace Cubed { class Player; - class Camera { private: - bool m_firse_mouse = true; Player* m_player; float m_last_mouse_x, m_last_mouse_y; glm::vec3 m_camera_pos; - public: - Camera(); void update_move_camera(); @@ -35,6 +31,4 @@ public: const glm::vec3& get_camera_pos() const; }; -} - - +} // namespace Cubed diff --git a/include/Cubed/config.hpp b/include/Cubed/config.hpp index 3f1b5fc..48f92e3 100644 --- a/include/Cubed/config.hpp +++ b/include/Cubed/config.hpp @@ -1,22 +1,16 @@ #pragma once -#include +#include "Cubed/tools/cubed_assert.hpp" -#include +#include namespace Cubed { - template -concept TomlValueType = - std::same_as || - std::same_as || - std::same_as || - std::same_as || - std::same_as || - std::same_as || - std::same_as || - std::same_as - ; +concept TomlValueType = + std::same_as || std::same_as || std::same_as || + std::same_as || std::same_as || + std::same_as || std::same_as || + std::same_as; class Config { public: @@ -30,8 +24,7 @@ public: void load_or_create_config(); void save_to_file(); - template - T get(std::string_view key) const{ + template T get(std::string_view key) const { size_t cur = 0; auto pos = key.find('.'); const toml::table* table = &m_tbl; @@ -59,7 +52,7 @@ public: std::abort(); } auto opt = (*table)[n_key].value(); - if (opt){ + if (opt) { return *opt; } else { Logger::error("Can't find key {}", n_key); @@ -67,11 +60,10 @@ public: std::abort(); } } - template - void set(std::string_view key, T&& val) { + template void set(std::string_view key, T&& val) { if constexpr (!TomlValueType>) { static_assert(false, "Type Not Support"); - } + } size_t cur = 0; auto pos = key.find('.'); toml::table* table = &m_tbl; @@ -90,7 +82,6 @@ public: auto [it, inserted] = table->insert_or_assign(s, toml::table{}); table = it->second.as_table(); } - } std::string_view n_key = key.substr(cur); if (n_key.empty()) { @@ -99,21 +90,18 @@ public: std::abort(); } table->insert_or_assign(n_key, std::forward(val)); - } - template - void set_and_save(std::string_view key, T&& val) { + template void set_and_save(std::string_view key, T&& val) { set(key, std::forward(val)); save_to_file(); } toml::node_view val_view(std::string_view key); private: - toml::table m_tbl; - constexpr static inline std::string_view CONGIF_PATH = ASSETS_PATH"config.toml"; + constexpr static inline std::string_view CONGIF_PATH = + ASSETS_PATH "config.toml"; void create_config(); - }; -} +} // namespace Cubed diff --git a/include/Cubed/constants.hpp b/include/Cubed/constants.hpp index 48ec76c..8e0efe9 100644 --- a/include/Cubed/constants.hpp +++ b/include/Cubed/constants.hpp @@ -18,10 +18,10 @@ constexpr int MAX_DISTANCE = 128; constexpr float DEFAULT_FOV = 70.0f; constexpr float DEFAULT_MAX_WALK_SPEED = 4.5f; constexpr float DEFAULT_MAX_RUN_SPEED = 7.0f; -constexpr float DEFAULT_ACCELERATION = 10.0f; +constexpr float DEFAULT_ACCELERATION = 10.0f; constexpr float DEFAULT_DECELERATION = 15.0f; constexpr float DEFAULT_G = 22.5f; using HeightMapArray = std::array, CHUCK_SIZE>; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/debug_collector.hpp b/include/Cubed/debug_collector.hpp index 6072896..6601c94 100644 --- a/include/Cubed/debug_collector.hpp +++ b/include/Cubed/debug_collector.hpp @@ -1,18 +1,16 @@ #pragma once -#include -#include +#include "Cubed/ui/text.hpp" #include namespace Cubed { - class DebugCollector { public: static DebugCollector& get(); DebugCollector(); - + std::unordered_map& all_texts(); Text& text(std::string_view name); @@ -23,4 +21,4 @@ private: std::unordered_map m_texts; }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/dev_panel.hpp b/include/Cubed/dev_panel.hpp index 0635bc3..1bd9bfe 100644 --- a/include/Cubed/dev_panel.hpp +++ b/include/Cubed/dev_panel.hpp @@ -29,11 +29,12 @@ class DevPanel { struct TextEditing { bool perlin_seed = false; }; + public: DevPanel(App& app); void init(); void render(); - + private: App& m_app; ConfigView m_config; @@ -50,8 +51,6 @@ private: void update_config_view(); void update_player_profile(); - }; - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/gameplay/biome.hpp b/include/Cubed/gameplay/biome.hpp index 6ce0c5f..e403d3e 100644 --- a/include/Cubed/gameplay/biome.hpp +++ b/include/Cubed/gameplay/biome.hpp @@ -12,14 +12,7 @@ constexpr float FOREST_FREQ = 1.2f; constexpr float DESERT_FREQ = 1.2f; constexpr float MOUNTAIN_FREQ = 2.0f; -enum class Biome { - PLAIN = 0, - FOREST, - DESERT, - MOUNTAIN, - NONE -}; - +enum class Biome { PLAIN = 0, FOREST, DESERT, MOUNTAIN, NONE }; struct BiomeHeightRange { int base_y; @@ -32,12 +25,11 @@ struct BiomeNonAdjacent { Biome replace; }; -static inline const std::vector NON_ADJACENT {{ - {Biome::PLAIN, {Biome::NONE}, Biome::PLAIN}, - {Biome::FOREST, {Biome::DESERT}, Biome::PLAIN}, - {Biome::DESERT, {Biome::MOUNTAIN, Biome::FOREST}, Biome::PLAIN}, - {Biome::MOUNTAIN, {Biome::DESERT}, Biome::PLAIN} -}}; +static inline const std::vector NON_ADJACENT{ + {{Biome::PLAIN, {Biome::NONE}, Biome::PLAIN}, + {Biome::FOREST, {Biome::DESERT}, Biome::PLAIN}, + {Biome::DESERT, {Biome::MOUNTAIN, Biome::FOREST}, Biome::PLAIN}, + {Biome::MOUNTAIN, {Biome::DESERT}, Biome::PLAIN}}}; struct BaseBiomeParams { Biome biome; @@ -47,32 +39,27 @@ struct BaseBiomeParams { BiomeHeightRange height_range; }; -struct PlainParams : public BaseBiomeParams { - -}; +struct PlainParams : public BaseBiomeParams {}; struct ForestParams : public BaseBiomeParams { float tree_frequency; }; -struct DesertParams : public BaseBiomeParams { +struct DesertParams : public BaseBiomeParams {}; -}; - -struct MountainParams : public BaseBiomeParams { - -}; +struct MountainParams : public BaseBiomeParams {}; std::string get_biome_str(Biome biome); Biome get_biome_from_noise(float temp, float humid); std::array get_noise_frequencies_for_biome(Biome biome); BiomeHeightRange get_biome_height_range(Biome biome); Biome safe_int_to_biome(int x); -int get_interpolated_height(float world_x, float world_z, float temp, float humid); +int get_interpolated_height(float world_x, float world_z, float temp, + float humid); PlainParams& plain_params(); ForestParams& forest_params(); DesertParams& desert_params(); MountainParams& mountain_params(); -} +} // namespace Cubed diff --git a/include/Cubed/gameplay/block.hpp b/include/Cubed/gameplay/block.hpp index abbc353..e369c51 100644 --- a/include/Cubed/gameplay/block.hpp +++ b/include/Cubed/gameplay/block.hpp @@ -1,26 +1,22 @@ #pragma once +#include "Cubed/constants.hpp" +#include "Cubed/tools/cubed_assert.hpp" + +#include #include #include -#include #include #include -#include -#include -#include - namespace Cubed { - struct BlockTexture { std::string name; unsigned id; std::vector texture; }; -struct Block : public BlockTexture{ - -}; +struct Block : public BlockTexture {}; struct BlockRenderData { std::vector draw_face; @@ -28,12 +24,8 @@ struct BlockRenderData { BlockRenderData() = default; BlockRenderData(const BlockRenderData&) = default; BlockRenderData& operator=(const BlockRenderData&) = default; - BlockRenderData(BlockRenderData&& data) : - draw_face(std::move(data.draw_face)), - block_id(data.block_id) - { - - } + BlockRenderData(BlockRenderData&& data) + : draw_face(std::move(data.draw_face)), block_id(data.block_id) {} BlockRenderData& operator=(BlockRenderData&& data) { draw_face = std::move(data.draw_face); block_id = data.block_id; @@ -47,29 +39,14 @@ struct LookBlock { }; constexpr std::array BLOCK_REISTER{ - "air", - "grass_block", - "dirt", - "stone", - "sand", - "log", - "leaf" -}; + "air", "grass_block", "dirt", "stone", "sand", "log", "leaf"}; -const std::array TRANSPARENT_MAP { - true, - false, - false, - false, - false, - false, - true -}; +const std::array TRANSPARENT_MAP{ + true, false, false, false, false, false, true}; inline bool is_in_transparent_map(unsigned id) { ASSERT_MSG(id < MAX_BLOCK_NUM, "ID is invaild"); return TRANSPARENT_MAP[id]; }; - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/gameplay/chunk.hpp b/include/Cubed/gameplay/chunk.hpp index 4b9469d..c8911d9 100644 --- a/include/Cubed/gameplay/chunk.hpp +++ b/include/Cubed/gameplay/chunk.hpp @@ -1,20 +1,18 @@ #pragma once +#include "Cubed/gameplay/biome.hpp" +#include "Cubed/gameplay/block.hpp" +#include "Cubed/gameplay/chunk_generator.hpp" +#include "Cubed/gameplay/chunk_pos.hpp" +#include "Cubed/primitive_data.hpp" + #include #include -#include -#include -#include -#include -#include -#include - namespace Cubed { - class World; -// if want to use, do init_chunk(), gen_vertex_data() and +// if want to use, do init_chunk(), gen_vertex_data() and class Chunk { private: static constexpr int SIZE_X = CHUCK_SIZE; @@ -22,13 +20,13 @@ private: static constexpr int SIZE_Z = CHUCK_SIZE; using HeightMapArray = std::array, SIZE_X>; - std::atomic m_dirty {false}; + std::atomic m_dirty{false}; std::atomic m_need_upload{true}; - std::atomic m_is_on_gen_vertex_data {false}; + std::atomic m_is_on_gen_vertex_data{false}; std::atomic m_vertex_sum = 0; std::atomic m_biome = Biome::PLAIN; std::mutex m_vertexs_data_mutex; - + std::unique_ptr m_generator; ChunkPos m_chunk_pos; @@ -38,7 +36,7 @@ private: std::vector m_blocks; GLuint m_vbo = 0; std::vector m_vertexs_data; - + float frequency = 0.01f; float height = 80; @@ -54,7 +52,7 @@ public: Biome get_biome() const; ChunkPos get_chunk_pos() const; - const std::vector& get_chunk_blocks() const; + const std::vector& get_chunk_blocks() const; HeightMapArray get_heightmap() const; static int get_index(int x, int y, int z); static int get_index(const glm::vec3& pos); @@ -66,32 +64,35 @@ public: // Generate heightmap using biome-specific noise void gen_phase_three(); // Blend heightmap with neighbors for smooth transitions - void gen_phase_four(const std::array, 4>& neighbor_heightmap); + void gen_phase_four( + const std::array, 4>& neighbor_heightmap); // Generate terrain blocks from heightmap and biome void gen_phase_five(); // Blend surface blocks at chunk borders with neighbors - void gen_phase_six(const std::array>, 4>& neighbor_block); + void gen_phase_six(const std::array>, 4>& + neighbor_block); // Generate biome-specific vegetation/structures void gen_phase_seven(); - //void gen_vertex_data(); - // 0 : (1, 0) - // 1 : (-1, 0) - // 2 : (0, 1) - // 3 : (0, -1) - void gen_vertex_data(const std::array*, 4>& neighbor_block); + // void gen_vertex_data(); + // 0 : (1, 0) + // 1 : (-1, 0) + // 2 : (0, 1) + // 3 : (0, -1) + void gen_vertex_data( + const std::array*, 4>& neighbor_block); void upload_to_gpu(); - + GLuint get_vbo() const; size_t get_vertex_sum() const; - + bool is_dirty() const; void mark_dirty(); - + bool is_need_upload() const; void need_upload(); void set_chunk_block(int index, unsigned id); - + ChunkPos chunk_pos() const; Biome biome() const; void biome(Biome b); @@ -99,5 +100,4 @@ public: std::vector& blocks(); }; - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/gameplay/chunk_generator.hpp b/include/Cubed/gameplay/chunk_generator.hpp index 2c4d4cb..6fc7de5 100644 --- a/include/Cubed/gameplay/chunk_generator.hpp +++ b/include/Cubed/gameplay/chunk_generator.hpp @@ -1,20 +1,21 @@ #pragma once -#include -#include +#include "Cubed/constants.hpp" +#include "Cubed/tools/cubed_random.hpp" #include #include namespace Cubed { - class Chunk; class ChunkGenerator { static constexpr int SIZE_X = CHUCK_SIZE; static constexpr int SIZE_Y = WORLD_SIZE_Y; static constexpr int SIZE_Z = CHUCK_SIZE; - using HeightMapArray = std::array, CHUCK_SIZE>; + using HeightMapArray = + std::array, CHUCK_SIZE>; + public: ChunkGenerator(Chunk& chunk); @@ -26,25 +27,28 @@ public: // Generate Biome void assign_chunk_biome(); // Adjust Biome - void resolve_biome_adjacency_conflict(const std::array& adj_chunks); + void resolve_biome_adjacency_conflict( + const std::array& adj_chunks); // Generate Heightmap void generate_heightmap(); // Adjust Height - void blend_heightmap_boundaries(const std::array, 4>& neighbor_heightmap); + void blend_heightmap_boundaries( + const std::array, 4>& neighbor_heightmap); // Generate Block void generate_terrain_blocks(); // Adjust Block; - void blend_surface_blocks_borders(const std::array>, 4>& neighbor_block); + void blend_surface_blocks_borders( + const std::array>, 4>& + neighbor_block); // Generate Structure void generate_vegetation(); private: - static inline std::atomic is_init {false}; - static inline unsigned m_generator_seed {0}; - static inline std::atomic is_seed_change {false}; + static inline std::atomic is_init{false}; + static inline unsigned m_generator_seed{0}; + static inline std::atomic is_seed_change{false}; Chunk& m_chunk; Random m_random; }; - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/gameplay/chunk_pos.hpp b/include/Cubed/gameplay/chunk_pos.hpp index 104cc5a..f1db40e 100644 --- a/include/Cubed/gameplay/chunk_pos.hpp +++ b/include/Cubed/gameplay/chunk_pos.hpp @@ -1,27 +1,23 @@ #pragma once + #include - -#include -#include - namespace Cubed { - struct ChunkPos { int x; int z; - + bool operator==(const ChunkPos&) const = default; struct Hash { - std::size_t operator()(const ChunkPos& pos) const{ + std::size_t operator()(const ChunkPos& pos) const { std::size_t h1 = std::hash{}(pos.x); std::size_t h2 = std::hash{}(pos.z); return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); } }; - ChunkPos operator+(const ChunkPos& pos) const{ + ChunkPos operator+(const ChunkPos& pos) const { return ChunkPos{x + pos.x, z + pos.z}; } @@ -32,5 +28,4 @@ struct ChunkPos { }; }; - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/gameplay/game_mode.hpp b/include/Cubed/gameplay/game_mode.hpp index ed2d5b6..5a317c0 100644 --- a/include/Cubed/gameplay/game_mode.hpp +++ b/include/Cubed/gameplay/game_mode.hpp @@ -5,22 +5,17 @@ namespace Cubed { - -enum class GameMode { - CREATIVE = 0, - SPECTATOR -}; +enum class GameMode { CREATIVE = 0, SPECTATOR }; inline std::string to_str(GameMode mode) { using enum GameMode; switch (mode) { - case CREATIVE: - return {"Creative"}; - case SPECTATOR: - return {"Spective"}; + case CREATIVE: + return {"Creative"}; + case SPECTATOR: + return {"Spective"}; } throw std::invalid_argument{"GameMode is invaild"}; } - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/gameplay/player.hpp b/include/Cubed/gameplay/player.hpp index 57e1567..976c753 100644 --- a/include/Cubed/gameplay/player.hpp +++ b/include/Cubed/gameplay/player.hpp @@ -1,23 +1,18 @@ #pragma once +#include "Cubed/AABB.hpp" +#include "Cubed/constants.hpp" +#include "Cubed/gameplay/block.hpp" +#include "Cubed/gameplay/chunk_pos.hpp" +#include "Cubed/gameplay/game_mode.hpp" +#include "Cubed/input.hpp" + #include - -#include -#include -#include -#include -#include -#include -#include - #include #include namespace Cubed { -enum class Gait{ - WALK = 0, - RUN -}; +enum class Gait { WALK = 0, RUN }; class World; @@ -26,46 +21,48 @@ private: using enum GameMode; float m_max_walk_speed = DEFAULT_MAX_WALK_SPEED; float m_max_run_speed = DEFAULT_MAX_RUN_SPEED; - float m_acceleration = DEFAULT_ACCELERATION; + float m_acceleration = DEFAULT_ACCELERATION; float m_deceleration = DEFAULT_DECELERATION; float m_g = DEFAULT_G; - constexpr static float MAX_SPACE_ON_TIME = 0.3f; + constexpr static float MAX_SPACE_ON_TIME = 0.3f; float m_yaw = 0.0f; float m_pitch = 0.0f; - + float m_sensitivity = 0.15f; float m_max_speed = m_max_walk_speed; float m_y_speed = 0.0f; bool can_up = true; - + float space_on_time = 0.0f; bool space_on = false; bool is_fly = false; - - float m_xz_speed = 0.0f; - - glm::vec3 direction = glm::vec3(0.0f, 0.0f, 0.0f); - glm::vec3 move_distance {0.0f, 0.0f, 0.0f}; - // player is tow block tall, the pos is the lower pos - - glm::vec3 m_player_pos {0.0f, 255.0f, 0.0f}; - ChunkPos m_player_chunk_pos {0, 0}; - glm::vec3 m_front {0, 0, -1}; - glm::vec3 m_right {0, 0, 0}; - glm::vec3 m_size {0.6f, 1.8f, 0.6f}; + float m_xz_speed = 0.0f; + + glm::vec3 direction = glm::vec3(0.0f, 0.0f, 0.0f); + glm::vec3 move_distance{0.0f, 0.0f, 0.0f}; + // player is tow block tall, the pos is the lower pos + + glm::vec3 m_player_pos{0.0f, 255.0f, 0.0f}; + ChunkPos m_player_chunk_pos{0, 0}; + + glm::vec3 m_front{0, 0, -1}; + glm::vec3 m_right{0, 0, 0}; + glm::vec3 m_size{0.6f, 1.8f, 0.6f}; Gait m_gait = Gait::WALK; - MoveState m_move_state {}; + MoveState m_move_state{}; GameMode m_game_mode = CREATIVE; std::optional m_look_block = std::nullopt; - std::string m_name {}; + std::string m_name{}; World& m_world; - bool ray_cast(const glm::vec3& start, const glm::vec3& dir, glm::ivec3& block_pos, glm::vec3& normal, float distance = 4.0f); + bool ray_cast(const glm::vec3& start, const glm::vec3& dir, + glm::ivec3& block_pos, glm::vec3& normal, + float distance = 4.0f); void check_player_chunk_transition(); void update_direction(); @@ -84,7 +81,7 @@ public: const std::optional& get_look_block_pos() const; const glm::vec3& get_player_pos() const; const MoveState& get_move_state() const; - + void change_mode(GameMode mode); void hot_reload(); void set_player_pos(const glm::vec3& pos); @@ -96,14 +93,12 @@ public: float& max_walk_speed(); float& max_run_speed(); float& max_speed(); - float& acceleration(); + float& acceleration(); float& deceleration(); float& g(); Gait& gait(); - GameMode& game_mode(); - + GameMode& game_mode(); }; - -} +} // namespace Cubed diff --git a/include/Cubed/gameplay/tree.hpp b/include/Cubed/gameplay/tree.hpp index 5327c22..da1f564 100644 --- a/include/Cubed/gameplay/tree.hpp +++ b/include/Cubed/gameplay/tree.hpp @@ -13,4 +13,4 @@ struct TreeStructNode { bool build_tree(Chunk& chunk, const glm::ivec3& pos); -} +} // namespace Cubed diff --git a/include/Cubed/gameplay/world.hpp b/include/Cubed/gameplay/world.hpp index 26e5ede..5fef3e0 100644 --- a/include/Cubed/gameplay/world.hpp +++ b/include/Cubed/gameplay/world.hpp @@ -1,14 +1,14 @@ #pragma once +#include "Cubed/AABB.hpp" +#include "Cubed/gameplay/chunk.hpp" + #include #include #include -#include #include +#include #include #include -#include -#include -#include namespace Cubed { @@ -19,18 +19,18 @@ struct ChunkRenderSnapshot { glm::vec3 half_extents; }; - class Player; class World { private: using ChunkPtrUpdateList = std::vector>; using ChunkUpdateList = std::vector>; - using ConstChunkMap = std::unordered_map; - using ChunkPosSet = std::unordered_set; + using ConstChunkMap = + std::unordered_map; + using ChunkPosSet = std::unordered_set; glm::vec3 m_gen_player_pos{0.0f, 0.0f, 0.0f}; - std::unordered_map m_chunks; + std::unordered_map m_chunks; std::unordered_map m_players; std::vector m_planes; @@ -44,7 +44,7 @@ private: std::condition_variable m_gen_cv; std::atomic m_gen_running{false}; std::atomic m_need_gen_chunk{false}; - std::atomic m_is_rebuilding {false}; + std::atomic m_is_rebuilding{false}; std::atomic m_could_gen{true}; std::atomic m_rendering_distance{24}; std::atomic m_chunk_gen_fraction{0.0f}; @@ -58,38 +58,44 @@ private: void gen_chunks_internal(); void sync_player_pos(glm::vec3& player_pos); void compute_required_chunks(ChunkPosSet& required_chunks); - void sync_and_collect_missing_chunks(std::vector& , const ChunkPosSet&); - void build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neighbor, ChunkPtrUpdateList& affected_neighbor, const ChunkUpdateList& new_chunks); - void build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList&, ConstChunkMap&); + void sync_and_collect_missing_chunks(std::vector&, + const ChunkPosSet&); + void + build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neighbor, + ChunkPtrUpdateList& affected_neighbor, + const ChunkUpdateList& new_chunks); + void build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList&, + ConstChunkMap&); void start_gen_thread(); void stop_gen_thread(); public: - World(); ~World(); bool can_move(const AABB& player_box) const; - //const BlockRenderData& get_block_render_data(int x, int y ,int z); - - const std::optional& get_look_block_pos(const std::string& name) const; + // const BlockRenderData& get_block_render_data(int x, int y ,int z); + + const std::optional& + get_look_block_pos(const std::string& name) const; const Chunk* get_chunk(const ChunkPos& pos) const; Player& get_player(const std::string& name); void init_world(); - bool is_aabb_in_frustum(const glm::vec3& center, const glm::vec3& half_extents); + bool is_aabb_in_frustum(const glm::vec3& center, + const glm::vec3& half_extents); int get_block(const glm::ivec3& block_pos) const; bool is_block(const glm::ivec3& block_pos) const; - + static ChunkPos chunk_pos(int world_x, int world_z); void need_gen(); void render(const glm::mat4& mvp_matrix); - + void set_block(const glm::ivec3& pos, unsigned id); void update(float delta_time); - + void push_delete_vbo(GLuint vbo); void hot_reload(); @@ -101,4 +107,4 @@ public: void rendering_distance(int rendering_distance); }; -} +} // namespace Cubed diff --git a/include/Cubed/input.hpp b/include/Cubed/input.hpp index 7902f2c..7183328 100644 --- a/include/Cubed/input.hpp +++ b/include/Cubed/input.hpp @@ -4,7 +4,6 @@ namespace Cubed { - struct MoveState { bool forward = false; bool back = false; @@ -30,10 +29,8 @@ struct InputState { }; namespace Input { - InputState& get_input_state(); +InputState& get_input_state(); - } - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/map_table.hpp b/include/Cubed/map_table.hpp index 0fc5393..618edbe 100644 --- a/include/Cubed/map_table.hpp +++ b/include/Cubed/map_table.hpp @@ -8,12 +8,12 @@ class MapTable { private: static std::unordered_map id_to_name_map; static std::unordered_map name_to_id_map; + public: // please using reference static const std::string& get_name_from_id(unsigned id); static unsigned get_id_from_name(const std::string& name); static void init_map(); - }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/primitive_data.hpp b/include/Cubed/primitive_data.hpp index 84dd58c..8b57b80 100644 --- a/include/Cubed/primitive_data.hpp +++ b/include/Cubed/primitive_data.hpp @@ -39,12 +39,12 @@ constexpr float VERTICES_POS[6][6][3] = { {0.0f, 1.0f, 1.0f}, // front left {0.0f, 1.0f, 0.0f}}, // back left // ===== bottom (y = -1) ===== - {{0.0f, 0.0f, 1.0f}, // front left - {1.0f, 0.0f, 1.0f}, // front right - {1.0f, 0.0f, 0.0f}, // back right - {1.0f, 0.0f, 0.0f}, // back right - {0.0f, 0.0f, 0.0f}, // back left - {0.0f, 0.0f, 1.0f}} // front left + {{0.0f, 0.0f, 1.0f}, // front left + {1.0f, 0.0f, 1.0f}, // front right + {1.0f, 0.0f, 0.0f}, // back right + {1.0f, 0.0f, 0.0f}, // back right + {0.0f, 0.0f, 0.0f}, // back left + {0.0f, 0.0f, 1.0f}} // front left }; constexpr float TEX_COORDS[6][6][2] = { @@ -84,49 +84,34 @@ constexpr float TEX_COORDS[6][6][2] = { {0.0f, 1.0f}, // front left {0.0f, 0.0f}}, // back left // ===== bottom (y = -1) ===== - {{0.0f, 0.0f}, // front left - {1.0f, 0.0f}, // front right - {1.0f, 1.0f}, // back right - {1.0f, 1.0f}, // back right - {0.0f, 1.0f}, // back left - {0.0f, 0.0f}} // front left + {{0.0f, 0.0f}, // front left + {1.0f, 0.0f}, // front right + {1.0f, 1.0f}, // back right + {1.0f, 1.0f}, // back right + {0.0f, 1.0f}, // back left + {0.0f, 0.0f}} // front left }; -constexpr float CUBE_VER[24] = { - 0.0, 0.0, 0.0, - 1.0, 0.0, 0.0, - 1.0, 1.0, 0.0, - 0.0, 1.0, 0.0, - 0.0, 0.0, 1.0, - 1.0, 0.0, 1.0, - 1.0, 1.0, 1.0, - 0.0, 1.0, 1.0 - }; +constexpr float CUBE_VER[24] = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, + 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, + 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0}; - -constexpr int OUTLINE_CUBE_INDICES[24] = { - 0,1, 1,2, 2,3, 3,0, - 4,5, 5,6, 6,7, 7,4, - 0,4, 1,5, 2,6, 3,7 - }; +constexpr int OUTLINE_CUBE_INDICES[24] = {0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, + 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7}; constexpr float SQUARE_VERTICES[6][2] = { - {-0.5f, -0.5f}, // bottom left - {-0.5f, 0.5f}, // top left - { 0.5f, 0.5f}, // top right - { 0.5f, 0.5f}, // top right - { 0.5f, -0.5f}, // bottom right - {-0.5f, -0.5f} // bottom left + {-0.5f, -0.5f}, // bottom left + {-0.5f, 0.5f}, // top left + {0.5f, 0.5f}, // top right + {0.5f, 0.5f}, // top right + {0.5f, -0.5f}, // bottom right + {-0.5f, -0.5f} // bottom left }; constexpr float SQUARE_TEXTURE_POS[6][2] = { - {0.0f, 0.0f}, - {0.0f, 1.0f}, - {1.0f, 1.0f}, - {1.0f, 1.0f}, - {1.0f, 0.0f}, - {0.0f, 0.0f}, - }; + {0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, + {1.0f, 1.0f}, {1.0f, 0.0f}, {0.0f, 0.0f}, +}; struct Vertex { float x = 0.0f, y = 0.0f, z = 0.0f; @@ -140,4 +125,4 @@ struct Vertex2D { float layer = 0.0f; }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/renderer.hpp b/include/Cubed/renderer.hpp index cd16044..18d2682 100644 --- a/include/Cubed/renderer.hpp +++ b/include/Cubed/renderer.hpp @@ -1,12 +1,10 @@ #pragma once -#include -#include -#include -#include -#include +#include "Cubed/constants.hpp" +#include "Cubed/primitive_data.hpp" +#include "Cubed/shader.hpp" +#include "Cubed/ui/text.hpp" -#include #include #include namespace Cubed { @@ -19,7 +17,8 @@ class Renderer { public: constexpr static int NUM_VAO = 5; - Renderer(const Camera& camera, World& world, const TextureManager& texture_manager, DevPanel& dev_panel); + Renderer(const Camera& camera, World& world, + const TextureManager& texture_manager, DevPanel& dev_panel); ~Renderer(); void hot_reload(); void init(); @@ -27,8 +26,8 @@ public: void render(); void update_fov(float fov); void update_proj_matrix(float aspect, float width, float height); + private: - const Camera& m_camera; DevPanel& m_dev_panel; const TextureManager& m_texture_manager; @@ -37,7 +36,7 @@ private: float m_aspect = 0.0f; float m_fov = DEFAULT_FOV; glm::mat4 m_p_mat, m_v_mat, m_m_mat, m_mv_mat, m_mvp_mat; - + GLuint m_mv_loc; GLuint m_proj_loc; @@ -57,10 +56,10 @@ private: void render_outline(); void render_sky(); - void render_text(); + void render_text(); void render_ui(); void render_world(); void render_dev_panel(); }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/shader.hpp b/include/Cubed/shader.hpp index aee1784..8c5b445 100644 --- a/include/Cubed/shader.hpp +++ b/include/Cubed/shader.hpp @@ -1,22 +1,22 @@ #pragma once #include - #include namespace Cubed { - class Shader { public: Shader(); - Shader(const std::string& name, const std::string& v_shader_path, const std::string& f_shader_path); + Shader(const std::string& name, const std::string& v_shader_path, + const std::string& f_shader_path); ~Shader(); Shader(const Shader&) = delete; Shader& operator=(const Shader&) = delete; Shader(Shader&& shader) noexcept; Shader& operator=(Shader&& shader) noexcept; - void create(const std::string& name, const std::string& v_shader_path, const std::string& f_shader_path); + void create(const std::string& name, const std::string& v_shader_path, + const std::string& f_shader_path); std::size_t hash() const; GLuint loc(const std::string& loc) const; const std::string& name() const; @@ -26,7 +26,6 @@ private: GLuint m_program = 0; std::size_t m_hash = 0; std::string m_name = "-1"; - }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/texture_manager.hpp b/include/Cubed/texture_manager.hpp index 7cf7523..63e845a 100644 --- a/include/Cubed/texture_manager.hpp +++ b/include/Cubed/texture_manager.hpp @@ -1,16 +1,15 @@ #pragma once +#include "Cubed/gameplay/block.hpp" + #include -#include -#include namespace Cubed { - class TextureManager { private: bool m_need_reload = false; GLuint m_block_status_array; - GLuint m_texture_array; + GLuint m_texture_array; GLuint m_ui_array; GLfloat m_max_aniso = 0.0f; int m_aniso = 1; @@ -21,8 +20,8 @@ private: public: TextureManager(); ~TextureManager(); - - void delet_texture(); + + void delet_texture(); GLuint get_block_status_array() const; GLuint get_texture_array() const; GLuint get_ui_array() const; @@ -34,5 +33,4 @@ public: int max_aniso() const; }; - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/tools/cubed_assert.hpp b/include/Cubed/tools/cubed_assert.hpp index 8281b5c..88fc448 100644 --- a/include/Cubed/tools/cubed_assert.hpp +++ b/include/Cubed/tools/cubed_assert.hpp @@ -1,37 +1,34 @@ #pragma once -#include +#include "Cubed/tools/log.hpp" namespace Cubed { - namespace Assert { - inline void msg(const char* condition, const char* file, - int line, const char* func, - std::string_view message = "" - ) { - - Logger::error("Assertion failed: {} at {}: {} in function {}", - condition, file, line, func); - if (message.size()) { - Logger::error("Message: {}", message); - } - std::abort(); +inline void msg(const char* condition, const char* file, int line, + const char* func, std::string_view message = "") { + Logger::error("Assertion failed: {} at {}: {} in function {}", condition, + file, line, func); + if (message.size()) { + Logger::error("Message: {}", message); } + std::abort(); } +} // namespace Assert #ifdef DEBUG_MODE -#define ASSERT(cond) \ - do { \ - if (!(cond)) { \ - ::Cubed::Assert::msg(#cond, __FILE__, __LINE__, __func__); \ - } \ +#define ASSERT(cond) \ + do { \ + if (!(cond)) { \ + ::Cubed::Assert::msg(#cond, __FILE__, __LINE__, __func__); \ + } \ } while (0) -#define ASSERT_MSG(cond, message) \ - do { \ - if (!(cond)) { \ - ::Cubed::Assert::msg(#cond, __FILE__, __LINE__, __func__, message); \ - } \ +#define ASSERT_MSG(cond, message) \ + do { \ + if (!(cond)) { \ + ::Cubed::Assert::msg(#cond, __FILE__, __LINE__, __func__, \ + message); \ + } \ } while (0) #else @@ -39,4 +36,4 @@ namespace Assert { #define ASSERT_MSG(cond, message) ((void)0) #endif -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/tools/cubed_hash.hpp b/include/Cubed/tools/cubed_hash.hpp index 3adfed4..b45061a 100644 --- a/include/Cubed/tools/cubed_hash.hpp +++ b/include/Cubed/tools/cubed_hash.hpp @@ -1,33 +1,32 @@ #pragma once -#include #include +#include namespace Cubed { - namespace HASH { - inline std::size_t str(std::string_view value) { - return std::hash{}(value); - } - inline uint32_t mix_hash(int32_t a, int32_t b, uint32_t fixed_seed) { - uint32_t h = fixed_seed; - - h ^= (uint32_t)a * 0xcc9e2d51u; - h = (h << 15) | (h >> 17); // rotl 15 - h *= 0x1b873593u; - - h ^= (uint32_t)b * 0xcc9e2d51u; - h = (h << 15) | (h >> 17); // rotl 15 - h *= 0x1b873593u; - - // Finalization(avalanche) - h ^= h >> 16; - h *= 0x85ebca6bu; - h ^= h >> 13; - h *= 0xc2b2ae35u; - h ^= h >> 16; - - return h; - } +inline std::size_t str(std::string_view value) { + return std::hash{}(value); } +inline uint32_t mix_hash(int32_t a, int32_t b, uint32_t fixed_seed) { + uint32_t h = fixed_seed; -} \ No newline at end of file + h ^= (uint32_t)a * 0xcc9e2d51u; + h = (h << 15) | (h >> 17); // rotl 15 + h *= 0x1b873593u; + + h ^= (uint32_t)b * 0xcc9e2d51u; + h = (h << 15) | (h >> 17); // rotl 15 + h *= 0x1b873593u; + + // Finalization(avalanche) + h ^= h >> 16; + h *= 0x85ebca6bu; + h ^= h >> 13; + h *= 0xc2b2ae35u; + h ^= h >> 16; + + return h; +} +} // namespace HASH + +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/tools/cubed_random.hpp b/include/Cubed/tools/cubed_random.hpp index c7cfb0a..de1b83f 100644 --- a/include/Cubed/tools/cubed_random.hpp +++ b/include/Cubed/tools/cubed_random.hpp @@ -17,5 +17,4 @@ private: std::mt19937 m_engine; }; - -} +} // namespace Cubed diff --git a/include/Cubed/tools/font.hpp b/include/Cubed/tools/font.hpp index c968ab7..fb3a4c1 100644 --- a/include/Cubed/tools/font.hpp +++ b/include/Cubed/tools/font.hpp @@ -2,17 +2,15 @@ #include #include FT_FREETYPE_H +#include "Cubed/primitive_data.hpp" + #include #include - #include #include -#include - namespace Cubed { - struct Character { glm::vec2 uv_min; glm::vec2 uv_max; @@ -28,9 +26,12 @@ public: Font(); ~Font(); - static std::vector vertices(const std::string& text, float x = 0.0f, float y = 0.0f, float scale = 1.0f); + static std::vector vertices(const std::string& text, + float x = 0.0f, float y = 0.0f, + float scale = 1.0f); static GLuint text_texture(); static const std::string& font_path(); + private: FT_Library m_ft; FT_Face m_face; @@ -39,13 +40,12 @@ private: float m_texture_height = 64; static inline GLuint m_text_texture; - static inline std::string m_font_path{ASSETS_PATH "fonts/IBMPlexSans-Regular.ttf"}; + static inline std::string m_font_path{ASSETS_PATH + "fonts/IBMPlexSans-Regular.ttf"}; std::unordered_map m_characters; void load_character(char8_t c); void setup_font_character(); - - }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/tools/log.hpp b/include/Cubed/tools/log.hpp index 3e8406e..783f68c 100644 --- a/include/Cubed/tools/log.hpp +++ b/include/Cubed/tools/log.hpp @@ -1,102 +1,85 @@ #pragma once -#include -#include #include #include +#include #include #include +#include namespace Cubed { namespace Logger { - enum class Level { - TRACE, - DEBUG, - INFO, - ERROR, - WARN - }; - - template - inline void info(std::format_string fmt, Args&&... args) { - auto now_time = std::chrono:: - time_point_cast - (std::chrono::system_clock::now()); - - std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); - std::osyncstream(std::cout) << "\033[1;32m" - << std::format("[INFO][{:%Y-%m-%d %H:%M:%S}]", now_time) - << msg - << "\033[0m" - << "\n"; - } - - template - inline void error(std::format_string fmt, Args&&... args) { - auto now_time = std::chrono:: - time_point_cast - (std::chrono::system_clock::now()); - std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); - std::osyncstream(std::cerr) << "\033[1;31m" - << std::format("[ERROR][{:%Y-%m-%d %H:%M:%S}]", now_time) - << msg - << "\033[0m" - << "\n"; - - } - - template - inline void warn(std::format_string fmt, Args&&... args) { - auto now_time = std::chrono:: - time_point_cast - (std::chrono::system_clock::now()); - std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); - std::osyncstream(std::cout) << "\033[1;33m" - << std::format("[WARN][{:%Y-%m-%d %H:%M:%S}]", now_time) - << msg - << "\033[0m" - << "\n"; - } - - template - inline void log(Level level, std::source_location loc, std::format_string fmt, Args&&... args) { - auto now_time = std::chrono:: - time_point_cast - (std::chrono::system_clock::now()); - std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); - switch (level) { - case Logger::Level::TRACE: - std::osyncstream(std::cout) << "\033[1;34m" - << std::format("[TRACE][{:%Y-%m-%d %H:%M:%S}]", now_time) - << "[" << loc.file_name() << ":" << loc.line() << "]" - << "[" << loc.function_name() << "]" - << msg - << "\033[0m" - << "\n"; - break; - case Logger::Level::DEBUG: - std::osyncstream(std::cout) << "\033[1;34m" - << std::format("[DEBUG][{:%Y-%m-%d %H:%M:%S}]", now_time) - << msg - << "\033[0m" - << "\n"; - break; - case Logger::Level::INFO: - info(fmt, std::forward(args)...); - break; - case Logger::Level::WARN: - warn(fmt, std::forward(args)...); - break; - case Logger::Level::ERROR: - error(fmt, std::forward(args)...); - break; - - } - - } - -} +enum class Level { TRACE, DEBUG, INFO, ERROR, WARN }; +template +inline void info(std::format_string fmt, Args&&... args) { + auto now_time = std::chrono::time_point_cast( + std::chrono::system_clock::now()); + std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); + std::osyncstream(std::cout) + << "\033[1;32m" << std::format("[INFO][{:%Y-%m-%d %H:%M:%S}]", now_time) + << msg << "\033[0m" + << "\n"; } +template +inline void error(std::format_string fmt, Args&&... args) { + auto now_time = std::chrono::time_point_cast( + std::chrono::system_clock::now()); + std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); + std::osyncstream(std::cerr) + << "\033[1;31m" + << std::format("[ERROR][{:%Y-%m-%d %H:%M:%S}]", now_time) << msg + << "\033[0m" + << "\n"; +} + +template +inline void warn(std::format_string fmt, Args&&... args) { + auto now_time = std::chrono::time_point_cast( + std::chrono::system_clock::now()); + std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); + std::osyncstream(std::cout) + << "\033[1;33m" << std::format("[WARN][{:%Y-%m-%d %H:%M:%S}]", now_time) + << msg << "\033[0m" + << "\n"; +} + +template +inline void log(Level level, std::source_location loc, + std::format_string fmt, Args&&... args) { + auto now_time = std::chrono::time_point_cast( + std::chrono::system_clock::now()); + std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); + switch (level) { + case Logger::Level::TRACE: + std::osyncstream(std::cout) + << "\033[1;34m" + << std::format("[TRACE][{:%Y-%m-%d %H:%M:%S}]", now_time) << "[" + << loc.file_name() << ":" << loc.line() << "]" + << "[" << loc.function_name() << "]" << msg << "\033[0m" + << "\n"; + break; + case Logger::Level::DEBUG: + std::osyncstream(std::cout) + << "\033[1;34m" + << std::format("[DEBUG][{:%Y-%m-%d %H:%M:%S}]", now_time) << msg + << "\033[0m" + << "\n"; + break; + case Logger::Level::INFO: + info(fmt, std::forward(args)...); + break; + case Logger::Level::WARN: + warn(fmt, std::forward(args)...); + break; + case Logger::Level::ERROR: + error(fmt, std::forward(args)...); + break; + } +} + +} // namespace Logger + +} // namespace Cubed diff --git a/include/Cubed/tools/math_tools.hpp b/include/Cubed/tools/math_tools.hpp index 9355f2a..b367560 100644 --- a/include/Cubed/tools/math_tools.hpp +++ b/include/Cubed/tools/math_tools.hpp @@ -3,9 +3,9 @@ namespace Cubed { - namespace Math { - void extract_frustum_planes(const glm::mat4& mvp_matrix, std::vector& planes); +void extract_frustum_planes(const glm::mat4& mvp_matrix, + std::vector& planes); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/tools/perlin_noise.hpp b/include/Cubed/tools/perlin_noise.hpp index d28d21f..078eef9 100644 --- a/include/Cubed/tools/perlin_noise.hpp +++ b/include/Cubed/tools/perlin_noise.hpp @@ -4,19 +4,18 @@ namespace Cubed { - class PerlinNoise { public: static void init(unsigned seed); static float noise(float x, float y, float z); static void reload(unsigned seed); + private: static inline std::atomic is_init = false; static inline std::vector p; static float fade(float t); static float lerp(float t, float a, float b); static float grad(int hash, float x, float y, float z); - }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/tools/shader_tools.hpp b/include/Cubed/tools/shader_tools.hpp index 229107d..0c6c151 100644 --- a/include/Cubed/tools/shader_tools.hpp +++ b/include/Cubed/tools/shader_tools.hpp @@ -1,21 +1,21 @@ #pragma once -#include #include +#include #include namespace Cubed { - namespace Tools { - GLuint create_shader_program(const std::string& v_shader_path, const std::string& f_shader_path); - void print_shader_log(GLuint shader); - void print_program_info(int prog); - bool check_opengl_error(); - std::string read_shader_source(const std::string& file_path); - void delete_image_data(unsigned char* data); - unsigned char* load_image_data(const std::string& tex_image_path); +GLuint create_shader_program(const std::string& v_shader_path, + const std::string& f_shader_path); +void print_shader_log(GLuint shader); +void print_program_info(int prog); +bool check_opengl_error(); +std::string read_shader_source(const std::string& file_path); +void delete_image_data(unsigned char* data); +unsigned char* load_image_data(const std::string& tex_image_path); -} +} // namespace Tools -} +} // namespace Cubed diff --git a/include/Cubed/tools/system_info.hpp b/include/Cubed/tools/system_info.hpp index 703c708..901199e 100644 --- a/include/Cubed/tools/system_info.hpp +++ b/include/Cubed/tools/system_info.hpp @@ -1,36 +1,39 @@ #pragma once +#include "Cubed/tools/log.hpp" + #include -#include #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN -#include #include -typedef LONG (WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); +#include +typedef LONG(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); #elif defined(__linux__) +#include #include #include -#include #endif namespace Cubed { - namespace Tools { inline bool get_os_version(std::string& str) { #ifdef _WIN32 HMODULE hntdll = GetModuleHandleW(L"ntdll.dll"); - if (!hntdll) return false; + if (!hntdll) + return false; auto prtl_get_version = reinterpret_cast( GetProcAddress(hntdll, "RtlGetVersion")); - if (!prtl_get_version) return false; + if (!prtl_get_version) + return false; - RTL_OSVERSIONINFOW osvi = { 0 }; + RTL_OSVERSIONINFOW osvi = {0}; osvi.dwOSVersionInfoSize = sizeof(osvi); - if (prtl_get_version(&osvi) != 0) return false; + if (prtl_get_version(&osvi) != 0) + return false; if (osvi.dwMajorVersion == 10) { if (osvi.dwBuildNumber >= 22000) { str = "Windows 11 Build " + std::to_string(osvi.dwBuildNumber); @@ -58,7 +61,7 @@ inline bool get_os_version(std::string& str) { continue; } str = line.substr(eq_pos + 1); - + if (str.size() >= 2 && str.front() == '"' && str.back() == '"') { str = str.substr(1, str.size() - 2); return true; @@ -74,7 +77,8 @@ inline bool get_os_version(std::string& str) { inline size_t get_current_rss() { #ifdef _WIN32 PROCESS_MEMORY_COUNTERS_EX pmc; - if (GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc))) { + if (GetProcessMemoryInfo(GetCurrentProcess(), + (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc))) { return pmc.WorkingSetSize; } return 0; @@ -94,19 +98,25 @@ inline std::string get_cpu_info() { #ifdef _WIN32 HKEY h_key; std::string cpu_name; - + if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, - L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", - 0, KEY_READ, &h_key) == ERROR_SUCCESS) { - + L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, + KEY_READ, &h_key) == ERROR_SUCCESS) { + DWORD dw_size = 0; - if (RegQueryValueExW(h_key, L"ProcessorNameString", NULL, NULL, NULL, &dw_size) == ERROR_SUCCESS && dw_size > 0) { + if (RegQueryValueExW(h_key, L"ProcessorNameString", NULL, NULL, NULL, + &dw_size) == ERROR_SUCCESS && + dw_size > 0) { std::vector buffer(dw_size / sizeof(wchar_t)); - if (RegQueryValueExW(h_key, L"ProcessorNameString", NULL, NULL, (LPBYTE)buffer.data(), &dw_size) == ERROR_SUCCESS) { - int len = WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, NULL, 0, NULL, NULL); + if (RegQueryValueExW(h_key, L"ProcessorNameString", NULL, NULL, + (LPBYTE)buffer.data(), + &dw_size) == ERROR_SUCCESS) { + int len = WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, + NULL, 0, NULL, NULL); if (len > 0) { std::vector narrow(len); - WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, narrow.data(), len, NULL, NULL); + WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, + narrow.data(), len, NULL, NULL); cpu_name = narrow.data(); } } @@ -117,7 +127,7 @@ inline std::string get_cpu_info() { cpu_name = "Unknown"; } return cpu_name; -#elif defined (__linux__) +#elif defined(__linux__) std::ifstream file("/proc/cpuinfo"); if (!file.is_open()) { return std::string{"Unkown"}; @@ -141,8 +151,6 @@ inline std::string get_cpu_info() { #endif } +} // namespace Tools -} - - -} +} // namespace Cubed diff --git a/include/Cubed/ui/color.hpp b/include/Cubed/ui/color.hpp index 5f8343b..33a6cb4 100644 --- a/include/Cubed/ui/color.hpp +++ b/include/Cubed/ui/color.hpp @@ -1,10 +1,10 @@ #pragma once -#include +#include "Cubed/tools/cubed_assert.hpp" + #include namespace Cubed { - enum class Color { BLACK, WHITE, @@ -25,37 +25,36 @@ inline constexpr glm::vec4 color_value(Color color) { using glm::vec4; switch (color) { - case Color::BLACK: - return vec4{0.0f, 0.0f, 0.0f, 1.0f}; - case Color::WHITE: - return vec4{1.0f, 1.0f, 1.0f, 1.0f}; - case Color::RED: - return vec4{1.0f, 0.0f, 0.0f, 1.0f}; - case Color::GREEN: - return vec4{0.0f, 1.0f, 0.0f, 1.0f}; - case Color::BLUE: - return vec4{0.0f, 0.0f, 1.0f, 1.0f}; - case Color::YELLOW: - return vec4{1.0f, 1.0f, 0.0f, 1.0f}; - case Color::CYAN: - return vec4{0.0f, 1.0f, 1.0f, 1.0f}; - case Color::MAGENTA: - return vec4{1.0f, 0.0f, 1.0f, 1.0f}; - case Color::GRAY: - return vec4{0.5f, 0.5f, 0.5f, 1.0f}; - case Color::ORANGE: - return vec4{1.0f, 0.647f, 0.0f, 1.0f}; - case Color::PURPLE: - return vec4{0.502f, 0.0f, 0.502f, 1.0f}; - case Color::PINK: - return vec4{1.0f, 0.753f, 0.769f, 1.0f}; - case Color::BROWN: - return vec4{0.647f, 0.165f, 0.165f, 1.0f}; - default: - ASSERT_MSG(false, "Unknown Color"); - return vec4{1.0f, 1.0f, 1.0f, 1.0f}; + case Color::BLACK: + return vec4{0.0f, 0.0f, 0.0f, 1.0f}; + case Color::WHITE: + return vec4{1.0f, 1.0f, 1.0f, 1.0f}; + case Color::RED: + return vec4{1.0f, 0.0f, 0.0f, 1.0f}; + case Color::GREEN: + return vec4{0.0f, 1.0f, 0.0f, 1.0f}; + case Color::BLUE: + return vec4{0.0f, 0.0f, 1.0f, 1.0f}; + case Color::YELLOW: + return vec4{1.0f, 1.0f, 0.0f, 1.0f}; + case Color::CYAN: + return vec4{0.0f, 1.0f, 1.0f, 1.0f}; + case Color::MAGENTA: + return vec4{1.0f, 0.0f, 1.0f, 1.0f}; + case Color::GRAY: + return vec4{0.5f, 0.5f, 0.5f, 1.0f}; + case Color::ORANGE: + return vec4{1.0f, 0.647f, 0.0f, 1.0f}; + case Color::PURPLE: + return vec4{0.502f, 0.0f, 0.502f, 1.0f}; + case Color::PINK: + return vec4{1.0f, 0.753f, 0.769f, 1.0f}; + case Color::BROWN: + return vec4{0.647f, 0.165f, 0.165f, 1.0f}; + default: + ASSERT_MSG(false, "Unknown Color"); + return vec4{1.0f, 1.0f, 1.0f, 1.0f}; } - } inline glm::vec4 rgb255_to_float(int r, int g, int b, int a) { @@ -67,4 +66,4 @@ inline glm::vec4 rgb255_to_float(int r, int g, int b, int a) { return glm::vec4{nr, ng, nb, na}; } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/ui/text.hpp b/include/Cubed/ui/text.hpp index b7533d7..a750363 100644 --- a/include/Cubed/ui/text.hpp +++ b/include/Cubed/ui/text.hpp @@ -1,32 +1,31 @@ #pragma once +#include "Cubed/primitive_data.hpp" +#include "Cubed/ui/color.hpp" + #include #include #include - -#include -#include -#include namespace Cubed { - class Shader; class Text { public: explicit Text(std::string_view name); - Text(std::string_view name, std::string_view str, glm::vec2 pos = glm::vec2{0.0f, 0.0f}, Color color = Color::BLACK); + Text(std::string_view name, std::string_view str, + glm::vec2 pos = glm::vec2{0.0f, 0.0f}, Color color = Color::BLACK); ~Text(); Text(const Text&) = delete; Text(Text&&) noexcept; Text& operator=(const Text&) = delete; Text& operator=(Text&&) noexcept = delete; Text& color(Color color); - //Text& color(const glm::vec4& color, int pos); + // Text& color(const glm::vec4& color, int pos); Text& position(float x, float y); Text& scale(float s); Text& text(std::string_view str); - + std::size_t uuid() const; static void set_loc(const Shader& shader); void render(); @@ -42,7 +41,7 @@ private: std::string m_text; glm::vec4 m_color{1.0f, 1.0f, 1.0f, 1.0f}; glm::mat4 m_model_matrix; - + std::vector m_vertices; GLuint m_vbo = 0; static inline GLuint m_color_loc = 0; @@ -50,7 +49,6 @@ private: void update_vertices(); void upload_to_gpu(); - }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/include/Cubed/window.hpp b/include/Cubed/window.hpp index 4c59667..6f8f95c 100644 --- a/include/Cubed/window.hpp +++ b/include/Cubed/window.hpp @@ -1,6 +1,7 @@ #pragma once +#define GLFW_INCLUDE_NONE #include -namespace Cubed{ +namespace Cubed { class Renderer; class Window { @@ -19,7 +20,7 @@ public: void toggle_fullscreen(); void toggle_mouse_able(); - + private: bool m_mouse_enable = false; float m_aspect; @@ -27,7 +28,6 @@ private: int m_width; int m_height; Renderer& m_renderer; - }; -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/app.cpp b/src/app.cpp index d418421..9b201dc 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -1,32 +1,26 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "Cubed/app.hpp" -#include +#include "Cubed/config.hpp" +#include "Cubed/debug_collector.hpp" +#include "Cubed/gameplay/player.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/log.hpp" +#include "Cubed/tools/system_info.hpp" #include +#include namespace Cubed { +App::App() {} -App::App() { - -} - -App::~App() { - -} -void App::cursor_position_callback(GLFWwindow* window, double xpos, double ypos) { +App::~App() {} +void App::cursor_position_callback(GLFWwindow* window, double xpos, + double ypos) { ImGuiIO& io = ImGui::GetIO(); - + App* app = static_cast(glfwGetWindowUserPointer(window)); - + ASSERT_MSG(app, "nullptr"); if (io.WantCaptureMouse && app->m_window.is_mouse_enable()) { ImGui_ImplGlfw_CursorPosCallback(window, xpos, ypos); @@ -35,7 +29,6 @@ void App::cursor_position_callback(GLFWwindow* window, double xpos, double ypos) if (!app->m_window.is_mouse_enable()) { app->m_camera.update_cursor_position_camera(xpos, ypos); } - } void App::init() { m_window.init(); @@ -43,21 +36,26 @@ void App::init() { Logger::info("Window Init Success"); glfwSetWindowUserPointer(m_window.get_glfw_window(), this); - - glfwSetCursorPosCallback(m_window.get_glfw_window(), cursor_position_callback); - glfwSetMouseButtonCallback(m_window.get_glfw_window(), mouse_button_callback); - glfwSetWindowFocusCallback(m_window.get_glfw_window(), window_focus_callback); - glfwSetWindowSizeCallback(m_window.get_glfw_window(), window_reshape_callback); + + glfwSetCursorPosCallback(m_window.get_glfw_window(), + cursor_position_callback); + glfwSetMouseButtonCallback(m_window.get_glfw_window(), + mouse_button_callback); + glfwSetWindowFocusCallback(m_window.get_glfw_window(), + window_focus_callback); + glfwSetWindowSizeCallback(m_window.get_glfw_window(), + window_reshape_callback); glfwSetKeyCallback(m_window.get_glfw_window(), key_callback); glfwSetScrollCallback(m_window.get_glfw_window(), mouse_scroll_callback); - glfwSetCursorEnterCallback(m_window.get_glfw_window(), cursor_enter_callback); + glfwSetCursorEnterCallback(m_window.get_glfw_window(), + cursor_enter_callback); glfwSetCharCallback(m_window.get_glfw_window(), char_callback); ChunkGenerator::init(); - + m_renderer.init(); Logger::info("Renderer Init Success"); m_window.update_viewport(); - //MapTable::init_map(); + // MapTable::init_map(); m_texture_manager.init_texture(); Logger::info("Texture Load Success"); m_world.init_world(); @@ -67,14 +65,17 @@ void App::init() { m_dev_panel.init(); } -void App::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { +void App::key_callback(GLFWwindow* window, int key, int scancode, int action, + int mods) { ImGuiIO& io = ImGui::GetIO(); - + App* app = static_cast(glfwGetWindowUserPointer(window)); ASSERT_MSG(app, "nullptr"); - //ImGui_ImplGlfw_CursorEnterCallback(window, !app->m_window.is_mouse_enable()); + // ImGui_ImplGlfw_CursorEnterCallback(window, + // !app->m_window.is_mouse_enable()); if (io.WantCaptureKeyboard && app->m_window.is_mouse_enable()) { - if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_ESCAPE) && action == GLFW_PRESS) { + if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_ESCAPE) && + action == GLFW_PRESS) { app->m_window.toggle_mouse_able(); app->m_camera.reset_camera(); return; @@ -82,39 +83,39 @@ void App::key_callback(GLFWwindow* window, int key, int scancode, int action, in ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mods); return; } - switch(key) { - case GLFW_KEY_Q: - if (action == GLFW_PRESS) { - } - break; - case GLFW_KEY_ESCAPE: - if (action == GLFW_PRESS) { - glfwSetWindowShouldClose(window, GLFW_TRUE); - } - break; - case GLFW_KEY_F11: - if (action == GLFW_PRESS) { - app->m_window.toggle_fullscreen(); - } - break; - case GLFW_KEY_R: - if (action == GLFW_PRESS) { - app->m_texture_manager.need_reload(); - } - break; - case GLFW_KEY_LEFT_ALT: - if (action == GLFW_PRESS) { - app->m_window.toggle_mouse_able(); - app->m_camera.reset_camera(); - } - break; - + switch (key) { + case GLFW_KEY_Q: + if (action == GLFW_PRESS) { + } + break; + case GLFW_KEY_ESCAPE: + if (action == GLFW_PRESS) { + glfwSetWindowShouldClose(window, GLFW_TRUE); + } + break; + case GLFW_KEY_F11: + if (action == GLFW_PRESS) { + app->m_window.toggle_fullscreen(); + } + break; + case GLFW_KEY_R: + if (action == GLFW_PRESS) { + app->m_texture_manager.need_reload(); + } + break; + case GLFW_KEY_LEFT_ALT: + if (action == GLFW_PRESS) { + app->m_window.toggle_mouse_able(); + app->m_camera.reset_camera(); + } + break; } app->m_world.get_player("TestPlayer").update_player_move_state(key, action); } -void App::mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { +void App::mouse_button_callback(GLFWwindow* window, int button, int action, + int mods) { ImGuiIO& io = ImGui::GetIO(); App* app = static_cast(glfwGetWindowUserPointer(window)); ASSERT_MSG(app, "nullptr"); @@ -123,27 +124,28 @@ void App::mouse_button_callback(GLFWwindow* window, int button, int action, int return; } switch (button) { - case GLFW_MOUSE_BUTTON_LEFT: - if (action == GLFW_PRESS) { - if(app->m_window.is_mouse_enable()) { - app->m_window.toggle_mouse_able(); - app->m_camera.reset_camera(); - break;; - } - Input::get_input_state().mouse_state.left = true; + case GLFW_MOUSE_BUTTON_LEFT: + if (action == GLFW_PRESS) { + if (app->m_window.is_mouse_enable()) { + app->m_window.toggle_mouse_able(); + app->m_camera.reset_camera(); + break; + ; } - if (action == GLFW_RELEASE) { - Input::get_input_state().mouse_state.left = false; - } - break; - case GLFW_MOUSE_BUTTON_RIGHT: - if (action == GLFW_PRESS) { - Input::get_input_state().mouse_state.right = true; - } - if (action == GLFW_RELEASE) { - Input::get_input_state().mouse_state.right = false; - } - break; + Input::get_input_state().mouse_state.left = true; + } + if (action == GLFW_RELEASE) { + Input::get_input_state().mouse_state.left = false; + } + break; + case GLFW_MOUSE_BUTTON_RIGHT: + if (action == GLFW_PRESS) { + Input::get_input_state().mouse_state.right = true; + } + if (action == GLFW_RELEASE) { + Input::get_input_state().mouse_state.right = false; + } + break; } } @@ -158,19 +160,20 @@ void App::window_focus_callback(GLFWwindow* window, int focused) { if (focused) { app->m_camera.reset_camera(); } - } -void App::window_reshape_callback(GLFWwindow* window, int new_width, int new_height) { - +void App::window_reshape_callback(GLFWwindow* window, int new_width, + int new_height) { + App* app = static_cast(glfwGetWindowUserPointer(window)); ASSERT_MSG(app, "nullptr"); app->m_window.update_viewport(); } -void App::mouse_scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { +void App::mouse_scroll_callback(GLFWwindow* window, double xoffset, + double yoffset) { ImGuiIO& io = ImGui::GetIO(); - + App* app = static_cast(glfwGetWindowUserPointer(window)); ASSERT_MSG(app, "nullptr"); if (io.WantCaptureMouse && app->m_window.is_mouse_enable()) { @@ -201,25 +204,23 @@ void App::char_callback(GLFWwindow* window, unsigned int c) { } void App::render() { - - if (glfwGetWindowAttrib(m_window.get_glfw_window(), GLFW_ICONIFIED) != 0) - { - ImGui_ImplGlfw_Sleep(10); - return; - } + + if (glfwGetWindowAttrib(m_window.get_glfw_window(), GLFW_ICONIFIED) != 0) { + ImGui_ImplGlfw_Sleep(10); + return; + } m_renderer.render(); glfwSwapBuffers(m_window.get_glfw_window()); } void App::run() { - + last_time = glfwGetTime(); - while(!glfwWindowShouldClose(m_window.get_glfw_window())) { - + while (!glfwWindowShouldClose(m_window.get_glfw_window())) { + update(); - render(); - + render(); } } static Gait player_gait = Gait::WALK; @@ -236,13 +237,16 @@ void App::update() { glfwSetWindowTitle(m_window.get_glfw_window(), title.c_str()); frame_count = 0; fps_time_count = 0.0f; - DebugCollector::get().report("fps", std::string{"FPS: " + std::to_string(fps)}); - DebugCollector::get().report("rss", std::format("RSS: {}mb", Tools::get_current_rss() / (1024 * 1024))); + DebugCollector::get().report( + "fps", std::string{"FPS: " + std::to_string(fps)}); + DebugCollector::get().report( + "rss", + std::format("RSS: {}mb", Tools::get_current_rss() / (1024 * 1024))); } m_texture_manager.update(); m_world.update(delta_time); m_camera.update_move_camera(); - const auto& player= m_world.get_player("TestPlayer"); + const auto& player = m_world.get_player("TestPlayer"); if (player_gait != player.get_gait()) { player_gait = player.get_gait(); float fov = static_cast(Config::get().get("player.fov")); @@ -253,7 +257,6 @@ void App::update() { m_renderer.update_fov(fov + 5.0f); } } - } int App::start_cubed_application(int argc, char** argv) { @@ -268,39 +271,22 @@ int App::start_cubed_application(int argc, char** argv) { return 0; } catch (std::exception& e) { Logger::error("{}", e.what()); - + } catch (...) { Logger::error("Unkown error"); - } return 1; } -float App::delte_time() { - return delta_time; -} +float App::delte_time() { return delta_time; } -float App::get_fps() { - return fps; -} +float App::get_fps() { return fps; } -Camera& App::camera() { - return m_camera; -} -DevPanel& App::dev_panel() { - return m_dev_panel; -} -Renderer& App::renderer() { - return m_renderer; -} -TextureManager& App::texture_manager() { - return m_texture_manager; -} -Window& App::window() { - return m_window; -} -World& App::world() { - return m_world; -} +Camera& App::camera() { return m_camera; } +DevPanel& App::dev_panel() { return m_dev_panel; } +Renderer& App::renderer() { return m_renderer; } +TextureManager& App::texture_manager() { return m_texture_manager; } +Window& App::window() { return m_window; } +World& App::world() { return m_world; } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/camera.cpp b/src/camera.cpp index dbf776e..bca6810 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -1,13 +1,11 @@ -#include -#include -#include +#include "Cubed/camera.hpp" + +#include "Cubed/gameplay/player.hpp" +#include "Cubed/tools/cubed_assert.hpp" namespace Cubed { - -Camera::Camera() { - -} +Camera::Camera() {} void Camera::update_move_camera() { ASSERT_MSG(m_player, "nullptr"); @@ -16,7 +14,6 @@ void Camera::update_move_camera() { m_camera_pos = glm::vec3(pos.x, pos.y + 1.6f, pos.z); } - void Camera::camera_init(Player* player) { m_player = player; update_move_camera(); @@ -24,13 +21,9 @@ void Camera::camera_init(Player* player) { hot_reload(); } -void Camera::hot_reload() { +void Camera::hot_reload() {} -} - -void Camera::reset_camera() { - m_firse_mouse = true; -} +void Camera::reset_camera() { m_firse_mouse = true; } void Camera::update_cursor_position_camera(double xpos, double ypos) { if (m_firse_mouse) { @@ -49,14 +42,12 @@ void Camera::update_cursor_position_camera(double xpos, double ypos) { m_player->update_front_vec(offset_x, offset_y); } -const glm::mat4 Camera::get_camera_lookat() const{ +const glm::mat4 Camera::get_camera_lookat() const { ASSERT_MSG(m_player, "nullptr"); - return glm::lookAt(m_camera_pos, m_camera_pos + m_player->get_front(), glm::vec3(0.0f, 1.0f, 0.0f)); + return glm::lookAt(m_camera_pos, m_camera_pos + m_player->get_front(), + glm::vec3(0.0f, 1.0f, 0.0f)); } -const glm::vec3& Camera::get_camera_pos() const { - return m_camera_pos; -} +const glm::vec3& Camera::get_camera_pos() const { return m_camera_pos; } - -} +} // namespace Cubed diff --git a/src/config.cpp b/src/config.cpp index feffa45..01cf6e1 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -1,6 +1,7 @@ -#include -#include -#include +#include "Cubed/config.hpp" + +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/log.hpp" #include #include @@ -10,22 +11,16 @@ using namespace std::string_view_literals; namespace Cubed { -Config::Config() { - load_or_create_config(); -} +Config::Config() { load_or_create_config(); } -Config::~Config() { - save_to_file(); -} +Config::~Config() { save_to_file(); } Config& Config::get() { static Config instance; return instance; } -toml::table& Config::table() { - return m_tbl; -} +toml::table& Config::table() { return m_tbl; } void Config::create_config() { static constexpr auto SOURCE = R"( @@ -60,26 +55,25 @@ void Config::create_config() { std::abort(); } Logger::info("Create New Config File Success"); - } void Config::load_or_create_config() { - fs::path config_path {CONGIF_PATH}; + fs::path config_path{CONGIF_PATH}; if (!fs::is_regular_file(config_path)) { create_config(); - } else try { - m_tbl = toml::parse_file(config_path.string()); - } catch (const toml::parse_error& err) { - Logger::error("Load Config Error: \"{}\"", err.what()); - create_config(); - } - - Logger::info("Load Config File Success"); + } else + try { + m_tbl = toml::parse_file(config_path.string()); + } catch (const toml::parse_error& err) { + Logger::error("Load Config Error: \"{}\"", err.what()); + create_config(); + } + Logger::info("Load Config File Success"); } void Config::save_to_file() { - fs::path config_path {CONGIF_PATH}; + fs::path config_path{CONGIF_PATH}; std::ofstream file{config_path}; file << m_tbl; Logger::info("Save File Success"); @@ -121,4 +115,4 @@ toml::node_view Config::val_view(std::string_view key) { return view; } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/debug_collector.cpp b/src/debug_collector.cpp index dfa8005..3a399ed 100644 --- a/src/debug_collector.cpp +++ b/src/debug_collector.cpp @@ -1,15 +1,12 @@ -#include +#include "Cubed/debug_collector.hpp" -#include -#include -#include +#include "Cubed/config.hpp" +#include "Cubed/tools/cubed_hash.hpp" +#include "Cubed/tools/system_info.hpp" namespace Cubed { - -DebugCollector::DebugCollector() { - -} +DebugCollector::DebugCollector() {} DebugCollector& DebugCollector::get() { static DebugCollector instance; @@ -27,70 +24,54 @@ void DebugCollector::init_text() { Text opengl_version_text("opengl_version"); Text biome_text("biome"); Text speed_text("speed"); - version_text - .position(0.0f, 100.0f) + version_text.position(0.0f, 100.0f) .scale(0.8f) .color(Color::WHITE) .text("Version: " + Config::get().get("version")); - fps_text - .position(0.0f, 50.0f) - .text("FPS: 0"); - player_pos_text - .position(0.0f, 150.0f) + fps_text.position(0.0f, 50.0f).text("FPS: 0"); + player_pos_text.position(0.0f, 150.0f) .scale(0.8f) .text("x: 0.00 y: 0.00 z: 0.00"); - rendered_chunk_text - .text("Rendered Chunk: 0") + rendered_chunk_text.text("Rendered Chunk: 0") .scale(0.8f) .position(0.0, 200.0f); - rss_text - .text("RSS: 0mb") - .scale(0.8f) - .position(0.0f, 300.0f); + rss_text.text("RSS: 0mb").scale(0.8f).position(0.0f, 300.0f); std::string os; - + Text os_text("os"); - os_text - .scale(0.8f) - .position(0.0f, 250.0f); + os_text.scale(0.8f).position(0.0f, 250.0f); if (Tools::get_os_version(os)) { - os_text - .text("OS: " + os); + os_text.text("OS: " + os); Logger::info("System: {}", os); } else { - os_text - .text("OS: Unknown"); - + os_text.text("OS: Unknown"); } - cpu_text - .text("CPU: " + Tools::get_cpu_info()) + cpu_text.text("CPU: " + Tools::get_cpu_info()) .scale(0.7f) .position(0.0f, 350.0f); gpu_text - .text(std::string{"GPU: "} + reinterpret_cast(glGetString(GL_RENDERER))) + .text(std::string{"GPU: "} + + reinterpret_cast(glGetString(GL_RENDERER))) .scale(0.7f) .position(0.0f, 400.0f); opengl_version_text - .text("OpenGL: " + std::to_string(GLVersion.major) + "." + std::to_string(GLVersion.minor)) + .text("OpenGL: " + std::to_string(GLVersion.major) + "." + + std::to_string(GLVersion.minor)) .scale(0.7f) .position(0.0f, 450.0f); - biome_text - .text("Biome: ") - .scale(0.8f) - .position(0.0f, 500.0f); - speed_text - .text("Speed: 0 m/s") - .scale(0.8f) - .position(0.0f, 550.0f); + biome_text.text("Biome: ").scale(0.8f).position(0.0f, 500.0f); + speed_text.text("Speed: 0 m/s").scale(0.8f).position(0.0f, 550.0f); m_texts.insert({version_text.uuid(), std::move(version_text)}); m_texts.insert({fps_text.uuid(), std::move(fps_text)}); m_texts.insert({player_pos_text.uuid(), std::move(player_pos_text)}); - m_texts.insert({rendered_chunk_text.uuid(), std::move(rendered_chunk_text)}); + m_texts.insert( + {rendered_chunk_text.uuid(), std::move(rendered_chunk_text)}); m_texts.insert({os_text.uuid(), std::move(os_text)}); m_texts.insert({rss_text.uuid(), std::move(rss_text)}); m_texts.insert({cpu_text.uuid(), std::move(cpu_text)}); m_texts.insert({gpu_text.uuid(), std::move(gpu_text)}); - m_texts.insert({opengl_version_text.uuid(), std::move(opengl_version_text)}); + m_texts.insert( + {opengl_version_text.uuid(), std::move(opengl_version_text)}); m_texts.insert({biome_text.uuid(), std::move(biome_text)}); m_texts.insert({speed_text.uuid(), std::move(speed_text)}); } @@ -100,7 +81,7 @@ std::unordered_map& DebugCollector::all_texts() { } Text& DebugCollector::text(std::string_view name) { - std::size_t id = HASH::str(name); + std::size_t id = HASH::str(name); auto it = m_texts.find(id); ASSERT_MSG(it != m_texts.end(), "Can't Find Text"); return it->second; @@ -111,4 +92,4 @@ void DebugCollector::report(std::string_view name, std::string_view content) { t.text(content); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/dev_panel.cpp b/src/dev_panel.cpp index 4a3f0a5..32707c5 100644 --- a/src/dev_panel.cpp +++ b/src/dev_panel.cpp @@ -1,8 +1,9 @@ -#include -#include -#include -#include -#include +#include "Cubed/dev_panel.hpp" + +#include "Cubed/app.hpp" +#include "Cubed/config.hpp" +#include "Cubed/gameplay/player.hpp" +#include "Cubed/tools/log.hpp" #include #include @@ -42,11 +43,7 @@ static int filter_unsigned(ImGuiInputTextCallbackData* data) { return 0; } -DevPanel::DevPanel(App& app) : - m_app(app) -{ - -} +DevPanel::DevPanel(App& app) : m_app(app) {} void DevPanel::init() { m_player = &m_app.world().get_player("TestPlayer"); @@ -63,15 +60,14 @@ void DevPanel::render() { continue; } */ - - + // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); - ImGui::Begin("DevPanel"); - ImGui::Text("This is a DevPanel to control the game\n"); + ImGui::Begin("DevPanel"); + ImGui::Text("This is a DevPanel to control the game\n"); if (ImGui::BeginTabBar("Menu")) { show_settings_tab_item(); show_world_tab_item(); @@ -79,15 +75,15 @@ void DevPanel::render() { show_about_table_bar(); ImGui::EndTabBar(); } - ImGui::End(); + ImGui::End(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - } void DevPanel::show_about_table_bar() { if (ImGui::BeginTabItem("about")) { - ImGui::Text("Cubed - A cube game like Minecraft, using C++ and OpenGL."); + ImGui::Text( + "Cubed - A cube game like Minecraft, using C++ and OpenGL."); ImGui::Text("Author: zhenyan121"); ImGui::Separator(); ImGui::Text("Libraries Used"); @@ -112,52 +108,116 @@ void DevPanel::show_biome_table_bar() { ImGui::Text("Biome"); if (ImGui::BeginTabBar("Biome")) { if (ImGui::BeginTabItem("Plain")) { - ImGui::SliderFloat("MinTemp##plain", &plain_params().temp.first, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MaxTemp##plain", &plain_params().temp.second, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MinHumid##plain", &plain_params().humid.first, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("MaxHumid##plain", &plain_params().humid.second, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("Freq One##plain", &plain_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); - ImGui::SliderFloat("Freq Two##plain", &plain_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); - ImGui::SliderFloat("Freq Three##plain", &plain_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); - ImGui::SliderInt("Base Y##plain", &plain_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); - ImGui::SliderInt("Amplitude##plain", &plain_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX); + ImGui::SliderFloat("MinTemp##plain", &plain_params().temp.first, + TEMP_MIN, TEMP_MAX); + ImGui::SliderFloat("MaxTemp##plain", &plain_params().temp.second, + TEMP_MIN, TEMP_MAX); + ImGui::SliderFloat("MinHumid##plain", &plain_params().humid.first, + HUMID_MIN, HUMID_MAX); + ImGui::SliderFloat("MaxHumid##plain", &plain_params().humid.second, + HUMID_MIN, HUMID_MAX); + ImGui::SliderFloat("Freq One##plain", + &plain_params().frequencies[0], FREQ1_MIN, + FREQ1_MAX); + ImGui::SliderFloat("Freq Two##plain", + &plain_params().frequencies[1], FREQ2_MIN, + FREQ2_MAX); + ImGui::SliderFloat("Freq Three##plain", + &plain_params().frequencies[2], FREQ3_MIN, + FREQ3_MAX); + ImGui::SliderInt("Base Y##plain", + &plain_params().height_range.base_y, + HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); + ImGui::SliderInt("Amplitude##plain", + &plain_params().height_range.amplitude, + AMPLITUDE_MIN, AMPLITUDE_MAX); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Forest")) { - ImGui::SliderFloat("MinTemp##forest", &forest_params().temp.first, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MaxTemp##forest", &forest_params().temp.second, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MinHumid##forest", &forest_params().humid.first, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("MaxHumid##forest", &forest_params().humid.second, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("Freq One##forest", &forest_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); - ImGui::SliderFloat("Freq Two##forest", &forest_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); - ImGui::SliderFloat("Freq Three##forest", &forest_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); - ImGui::SliderInt("Base Y##forest", &forest_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); - ImGui::SliderInt("Amplitude##forest", &forest_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX); - ImGui::SliderFloat("Tree Freq##forest", &forest_params().tree_frequency, TREE_FREQ_MIM, TREE_FREQ_MAX); + ImGui::SliderFloat("MinTemp##forest", &forest_params().temp.first, + TEMP_MIN, TEMP_MAX); + ImGui::SliderFloat("MaxTemp##forest", &forest_params().temp.second, + TEMP_MIN, TEMP_MAX); + ImGui::SliderFloat("MinHumid##forest", &forest_params().humid.first, + HUMID_MIN, HUMID_MAX); + ImGui::SliderFloat("MaxHumid##forest", + &forest_params().humid.second, HUMID_MIN, + HUMID_MAX); + ImGui::SliderFloat("Freq One##forest", + &forest_params().frequencies[0], FREQ1_MIN, + FREQ1_MAX); + ImGui::SliderFloat("Freq Two##forest", + &forest_params().frequencies[1], FREQ2_MIN, + FREQ2_MAX); + ImGui::SliderFloat("Freq Three##forest", + &forest_params().frequencies[2], FREQ3_MIN, + FREQ3_MAX); + ImGui::SliderInt("Base Y##forest", + &forest_params().height_range.base_y, + HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); + ImGui::SliderInt("Amplitude##forest", + &forest_params().height_range.amplitude, + AMPLITUDE_MIN, AMPLITUDE_MAX); + ImGui::SliderFloat("Tree Freq##forest", + &forest_params().tree_frequency, TREE_FREQ_MIM, + TREE_FREQ_MAX); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Desert")) { - ImGui::SliderFloat("MinTemp##desert", &desert_params().temp.first, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MaxTemp##desert", &desert_params().temp.second, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MinHumid##desert", &desert_params().humid.first, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("MaxHumid##desert", &desert_params().humid.second, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("Freq One##desert", &desert_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); - ImGui::SliderFloat("Freq Two##desert", &desert_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); - ImGui::SliderFloat("Freq Three##desert", &desert_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); - ImGui::SliderInt("Base Y##desert", &desert_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); - ImGui::SliderInt("Amplitude##desert", &desert_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX); + ImGui::SliderFloat("MinTemp##desert", &desert_params().temp.first, + TEMP_MIN, TEMP_MAX); + ImGui::SliderFloat("MaxTemp##desert", &desert_params().temp.second, + TEMP_MIN, TEMP_MAX); + ImGui::SliderFloat("MinHumid##desert", &desert_params().humid.first, + HUMID_MIN, HUMID_MAX); + ImGui::SliderFloat("MaxHumid##desert", + &desert_params().humid.second, HUMID_MIN, + HUMID_MAX); + ImGui::SliderFloat("Freq One##desert", + &desert_params().frequencies[0], FREQ1_MIN, + FREQ1_MAX); + ImGui::SliderFloat("Freq Two##desert", + &desert_params().frequencies[1], FREQ2_MIN, + FREQ2_MAX); + ImGui::SliderFloat("Freq Three##desert", + &desert_params().frequencies[2], FREQ3_MIN, + FREQ3_MAX); + ImGui::SliderInt("Base Y##desert", + &desert_params().height_range.base_y, + HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); + ImGui::SliderInt("Amplitude##desert", + &desert_params().height_range.amplitude, + AMPLITUDE_MIN, AMPLITUDE_MAX); ImGui::EndTabItem(); } if (ImGui::BeginTabItem("Mountain")) { - ImGui::SliderFloat("MinTemp##mountain", &mountain_params().temp.first, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MaxTemp##mountain", &mountain_params().temp.second, TEMP_MIN, TEMP_MAX); - ImGui::SliderFloat("MinHumid##mountain", &mountain_params().humid.first, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("MaxHumid##mountain", &mountain_params().humid.second, HUMID_MIN, HUMID_MAX); - ImGui::SliderFloat("Freq One##mountain", &mountain_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); - ImGui::SliderFloat("Freq Two##mountain", &mountain_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); - ImGui::SliderFloat("Freq Three##mountain", &mountain_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); - ImGui::SliderInt("Base Y##mountain", &mountain_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); - ImGui::SliderInt("Amplitude##mountain", &mountain_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX); + ImGui::SliderFloat("MinTemp##mountain", + &mountain_params().temp.first, TEMP_MIN, + TEMP_MAX); + ImGui::SliderFloat("MaxTemp##mountain", + &mountain_params().temp.second, TEMP_MIN, + TEMP_MAX); + ImGui::SliderFloat("MinHumid##mountain", + &mountain_params().humid.first, HUMID_MIN, + HUMID_MAX); + ImGui::SliderFloat("MaxHumid##mountain", + &mountain_params().humid.second, HUMID_MIN, + HUMID_MAX); + ImGui::SliderFloat("Freq One##mountain", + &mountain_params().frequencies[0], FREQ1_MIN, + FREQ1_MAX); + ImGui::SliderFloat("Freq Two##mountain", + &mountain_params().frequencies[1], FREQ2_MIN, + FREQ2_MAX); + ImGui::SliderFloat("Freq Three##mountain", + &mountain_params().frequencies[2], FREQ3_MIN, + FREQ3_MAX); + ImGui::SliderInt("Base Y##mountain", + &mountain_params().height_range.base_y, + HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); + ImGui::SliderInt("Amplitude##mountain", + &mountain_params().height_range.amplitude, + AMPLITUDE_MIN, AMPLITUDE_MAX); ImGui::EndTabItem(); } ImGui::EndTabBar(); @@ -166,7 +226,7 @@ void DevPanel::show_biome_table_bar() { void DevPanel::show_settings_tab_item() { if (ImGui::BeginTabItem("settings")) { - if(ImGui::SliderFloat("FOV", &m_config.fov, 1.0f, 140.0f)) { + if (ImGui::SliderFloat("FOV", &m_config.fov, 1.0f, 140.0f)) { Config::get().set("player.fov", static_cast(m_config.fov)); m_app.renderer().hot_reload(); } @@ -176,18 +236,23 @@ void DevPanel::show_settings_tab_item() { Config::get().set("player.fov", static_cast(m_config.fov)); m_app.renderer().hot_reload(); } - if (ImGui::SliderFloat("Sensitivity", &m_config.mouse_sensitivity, 0.01f, 1.0f)) { - Config::get().set("player.mouse_sensitivity", static_cast(m_config.mouse_sensitivity)); + if (ImGui::SliderFloat("Sensitivity", &m_config.mouse_sensitivity, + 0.01f, 1.0f)) { + Config::get().set("player.mouse_sensitivity", + static_cast(m_config.mouse_sensitivity)); m_player->hot_reload(); } ImGui::SameLine(); if (ImGui::Button("default##2")) { m_config.mouse_sensitivity = 0.15f; - Config::get().set("player.mouse_sensitivity", static_cast(m_config.mouse_sensitivity)); + Config::get().set("player.mouse_sensitivity", + static_cast(m_config.mouse_sensitivity)); m_player->hot_reload(); } - if (ImGui::SliderInt("Distance", &m_config.rendering_distance, 2, 128)) { - Config::get().set("world.rendering_distance", m_config.rendering_distance); + if (ImGui::SliderInt("Distance", &m_config.rendering_distance, 2, + 128)) { + Config::get().set("world.rendering_distance", + m_config.rendering_distance); m_app.world().hot_reload(); } if (ImGui::Checkbox("Fullscreen", &m_config.fullscreen)) { @@ -211,16 +276,17 @@ void DevPanel::show_settings_tab_item() { } else { m_config.aniso = 1; } - } if (m_config.is_enable_aniso) { ImGui::SameLine(); if (!m_config.is_support_aniso) { ImGui::Text("Not Support\n"); } else { - if (ImGui::SliderInt("##aniso", &m_config.aniso, 2, m_config.max_aniso)) { + if (ImGui::SliderInt("##aniso", &m_config.aniso, 2, + m_config.max_aniso)) { m_config.is_reload = false; - int log = static_cast(std::log2(m_config.aniso) + 0.5f); + int log = + static_cast(std::log2(m_config.aniso) + 0.5f); m_config.aniso = static_cast(std::pow(2, log)); if (m_config.aniso < 2) { m_config.aniso = 2; @@ -248,28 +314,27 @@ void DevPanel::show_settings_tab_item() { } Config::get().set("devpanel.theme", m_theme); } - if (ImGui::Button("save")) { + if (ImGui::Button("save")) { Config::get().save_to_file(); } - + ImGui::EndTabItem(); } - } void DevPanel::show_world_tab_item() { if (ImGui::BeginTabItem("world")) { if (m_text_editing.perlin_seed) { - if (ImGui::InputText("Perlin Noise Seed", perlin_noise_input_buffer, sizeof(perlin_noise_input_buffer), - ImGuiInputTextFlags_CallbackCharFilter | - ImGuiInputTextFlags_EnterReturnsTrue, - filter_unsigned)) - { - ChunkGenerator::seed(static_cast(std::strtoul(perlin_noise_input_buffer, nullptr, 10))); + if (ImGui::InputText("Perlin Noise Seed", perlin_noise_input_buffer, + sizeof(perlin_noise_input_buffer), + ImGuiInputTextFlags_CallbackCharFilter | + ImGuiInputTextFlags_EnterReturnsTrue, + filter_unsigned)) { + ChunkGenerator::seed(static_cast( + std::strtoul(perlin_noise_input_buffer, nullptr, 10))); m_text_editing.perlin_seed = false; m_player->set_player_pos({0.0f, 255.0f, 0.0f}); m_app.world().rebuild_world(); - } } if (!m_text_editing.perlin_seed) { @@ -306,7 +371,8 @@ void DevPanel::show_player_tab_item() { return; } if (ImGui::BeginTabItem("player")) { - if (ImGui::Combo("GameMode", &m_player_profile.game_mode, GAME_MODES, IM_ARRAYSIZE(GAME_MODES))) { + if (ImGui::Combo("GameMode", &m_player_profile.game_mode, GAME_MODES, + IM_ARRAYSIZE(GAME_MODES))) { if (m_player_profile.game_mode == 0) { m_player->change_mode(GameMode::CREATIVE); } else if (m_player_profile.game_mode == 1) { @@ -316,7 +382,8 @@ void DevPanel::show_player_tab_item() { } } if (m_player->game_mode() == GameMode::CREATIVE) { - if (ImGui::Combo("Gait", &m_player_profile.gait, GAITS, IM_ARRAYSIZE(GAITS))) { + if (ImGui::Combo("Gait", &m_player_profile.gait, GAITS, + IM_ARRAYSIZE(GAITS))) { if (m_player_profile.gait == 0) { m_player->gait() = Gait::WALK; } else if (m_player_profile.gait == 1) { @@ -329,50 +396,59 @@ void DevPanel::show_player_tab_item() { ImGui::DragFloat3("##player_pos", m_player_profile.pos); ImGui::SameLine(); if (ImGui::Button("TP")) { - m_player->set_player_pos({m_player_profile.pos[0], m_player_profile.pos[1], m_player_profile.pos[2]}); + m_player->set_player_pos({m_player_profile.pos[0], + m_player_profile.pos[1], + m_player_profile.pos[2]}); } - ImGui::SliderFloat("Acceleration", &m_player->acceleration(), 1.0f, 200.0f); - ImGui::SliderFloat("Deceleration", &m_player->deceleration(), 1.0f, 200.0f); + ImGui::SliderFloat("Acceleration", &m_player->acceleration(), 1.0f, + 200.0f); + ImGui::SliderFloat("Deceleration", &m_player->deceleration(), 1.0f, + 200.0f); if (m_player->game_mode() == GameMode::CREATIVE) { m_player_profile.game_mode = 0; - ImGui::SliderFloat("MaxWalkSpeed", &m_player->max_walk_speed(), 1.0f, 200.0f); - ImGui::SliderFloat("MaxRunSpeed", &m_player->max_run_speed(), 1.0f, 500.0f); + ImGui::SliderFloat("MaxWalkSpeed", &m_player->max_walk_speed(), + 1.0f, 200.0f); + ImGui::SliderFloat("MaxRunSpeed", &m_player->max_run_speed(), 1.0f, + 500.0f); ImGui::SliderFloat("G", &m_player->g(), 1.0f, 200.0f); - + } else if (m_player->game_mode() == GameMode::SPECTATOR) { m_player_profile.game_mode = 1; - ImGui::SliderFloat("MaxSpeed", &m_player->max_speed(), 1.0f, 500.0f); + ImGui::SliderFloat("MaxSpeed", &m_player->max_speed(), 1.0f, + 500.0f); } if (ImGui::Button("reset")) { - m_player->max_walk_speed() = DEFAULT_MAX_WALK_SPEED; - m_player->max_run_speed() = DEFAULT_MAX_RUN_SPEED; - m_player->acceleration() = DEFAULT_ACCELERATION; - m_player->deceleration() = DEFAULT_DECELERATION; - m_player->g() = DEFAULT_G; - m_player->change_mode(GameMode::CREATIVE); - m_player->gait() = Gait::WALK; - m_player_profile.game_mode = 0; - m_player_profile.gait = 0; - } + m_player->max_walk_speed() = DEFAULT_MAX_WALK_SPEED; + m_player->max_run_speed() = DEFAULT_MAX_RUN_SPEED; + m_player->acceleration() = DEFAULT_ACCELERATION; + m_player->deceleration() = DEFAULT_DECELERATION; + m_player->g() = DEFAULT_G; + m_player->change_mode(GameMode::CREATIVE); + m_player->gait() = Gait::WALK; + m_player_profile.game_mode = 0; + m_player_profile.gait = 0; + } if (m_player->gait() == Gait::WALK) { m_player_profile.gait = 0; } else { m_player_profile.gait = 1; } - - + ImGui::EndTabItem(); } } void DevPanel::update_config_view() { auto config = Config::get(); - m_config.fov = static_cast(config.val_view("player.fov").value_or(70.0)); + m_config.fov = + static_cast(config.val_view("player.fov").value_or(70.0)); m_config.fullscreen = config.val_view("window.fullscreen").value_or(false); m_config.v_sync = config.val_view("window.V-Sync").value_or(true); - m_config.mouse_sensitivity = static_cast(config.val_view("player.mouse_sensitivity").value_or(0.15)); + m_config.mouse_sensitivity = static_cast( + config.val_view("player.mouse_sensitivity").value_or(0.15)); m_config.width = config.val_view("window.width").value_or(800); m_config.height = config.val_view("window.height").value_or(600); - m_config.rendering_distance = config.val_view("world.rendering_distance").value_or(24); + m_config.rendering_distance = + config.val_view("world.rendering_distance").value_or(24); m_theme = config.val_view("devpanel.theme").value_or(0); if (m_theme != 1 && m_theme != 0) { m_theme = 0; @@ -395,4 +471,4 @@ void DevPanel::update_player_profile() { m_player_profile.game_mode = std::to_underlying(m_player->game_mode()); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/gameplay/biome.cpp b/src/gameplay/biome.cpp index b232cc3..96e28b9 100644 --- a/src/gameplay/biome.cpp +++ b/src/gameplay/biome.cpp @@ -1,74 +1,60 @@ -#include -#include -#include -#include +#include "Cubed/gameplay/biome.hpp" + +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/log.hpp" +#include "Cubed/tools/perlin_noise.hpp" #include #include namespace Cubed { -static PlainParams plain { - { - Biome::PLAIN, - {0.0f, 0.5f}, - {0.0f, 0.5f}, - {0.003f, 0.010f, 0.020f}, - {62, 8} - } -}; +static PlainParams plain{{Biome::PLAIN, + {0.0f, 0.5f}, + {0.0f, 0.5f}, + {0.003f, 0.010f, 0.020f}, + {62, 8}}}; -static ForestParams forest { - { - Biome::FOREST, - {0.5f, 1.0f}, - {0.5f, 1.0f}, - {0.004f, 0.010f, 0.020f}, - {64, 12} - }, - 0.1f +static ForestParams forest{{Biome::FOREST, + {0.5f, 1.0f}, + {0.5f, 1.0f}, + {0.004f, 0.010f, 0.020f}, + {64, 12}}, + 0.1f }; -static DesertParams desert { - { - Biome::DESERT, - {0.5f, 1.0f}, - {0.0f, 0.5f}, - {0.003f, 0.010f, 0.020f}, - {61, 12} - } -}; +static DesertParams desert{{Biome::DESERT, + {0.5f, 1.0f}, + {0.0f, 0.5f}, + {0.003f, 0.010f, 0.020f}, + {61, 12}}}; -static MountainParams mountain { - { - Biome::MOUNTAIN, - {0.0f, 0.5f}, - {0.5f, 1.0f}, - {0.006f, 0.014f, 0.010f}, - {70, 70} - } -}; +static MountainParams mountain{{Biome::MOUNTAIN, + {0.0f, 0.5f}, + {0.5f, 1.0f}, + {0.006f, 0.014f, 0.010f}, + {70, 70}}}; std::string get_biome_str(Biome biome) { std::string str; using enum Biome; switch (biome) { - case PLAIN: - str = "Plain"; - break; - case FOREST: - str = "Forest"; - break; - case DESERT: - str = "Desert"; - break; - case MOUNTAIN: - str = "Mountain"; - break; - case NONE: - str = "Unknown"; - break; + case PLAIN: + str = "Plain"; + break; + case FOREST: + str = "Forest"; + break; + case DESERT: + str = "Desert"; + break; + case MOUNTAIN: + str = "Mountain"; + break; + case NONE: + str = "Unknown"; + break; } return str; }; @@ -78,7 +64,7 @@ Biome get_biome_from_noise(float temp, float humid) { float dt = t - ct; float dh = h - ch; float dist = std::sqrt(dt*dt + dh*dh); - return std::max(0.0f, 0.5f - dist); + return std::max(0.0f, 0.5f - dist); }; float w_m = weight(temp, humid, 0.25f, 0.15f); float w_p = weight(temp, humid, 0.50f, 0.40f); @@ -93,35 +79,39 @@ Biome get_biome_from_noise(float temp, float humid) { */ Biome get_biome_from_noise(float temp, float humid) { using enum Biome; - if (plain.temp.first <= temp && temp < plain.temp.second && plain.humid.first <= humid && humid < plain.humid.second) { + if (plain.temp.first <= temp && temp < plain.temp.second && + plain.humid.first <= humid && humid < plain.humid.second) { return PLAIN; } - if (forest.temp.first <= temp && temp < forest.temp.second && forest.humid.first <= humid && humid < forest.humid.second) { + if (forest.temp.first <= temp && temp < forest.temp.second && + forest.humid.first <= humid && humid < forest.humid.second) { return FOREST; } - if (desert.temp.first <= temp && temp < desert.temp.second && desert.humid.first <= humid && humid < desert.humid.second) { + if (desert.temp.first <= temp && temp < desert.temp.second && + desert.humid.first <= humid && humid < desert.humid.second) { return DESERT; } - if (mountain.temp.first <= temp && temp <= mountain.temp.second && mountain.humid.first <= humid && humid <= mountain.humid.second) { + if (mountain.temp.first <= temp && temp <= mountain.temp.second && + mountain.humid.first <= humid && humid <= mountain.humid.second) { return MOUNTAIN; } Logger::warn("Invail Temp {} or Humid {}", temp, humid); - return PLAIN; + return PLAIN; } std::array get_noise_frequencies_for_biome(Biome biome) { using enum Biome; switch (biome) { - case PLAIN: - return plain.frequencies; - case FOREST: - return forest.frequencies; - case DESERT: - return desert.frequencies; - case MOUNTAIN: - return mountain.frequencies; - case NONE: - ASSERT_MSG(false, "Chunk Biome is None"); - throw std::invalid_argument{"Chunk Biome is None"}; + case PLAIN: + return plain.frequencies; + case FOREST: + return forest.frequencies; + case DESERT: + return desert.frequencies; + case MOUNTAIN: + return mountain.frequencies; + case NONE: + ASSERT_MSG(false, "Chunk Biome is None"); + throw std::invalid_argument{"Chunk Biome is None"}; } Logger::warn("Unknown Biome"); return {0.003f, 0.015f, 0.06f}; @@ -130,17 +120,17 @@ std::array get_noise_frequencies_for_biome(Biome biome) { BiomeHeightRange get_biome_height_range(Biome biome) { using enum Biome; switch (biome) { - case PLAIN: - return plain.height_range; - case FOREST: - return forest.height_range; - case DESERT: - return desert.height_range; - case MOUNTAIN: - return mountain.height_range; - case NONE: - ASSERT_MSG(false, "Chunk Biome is None"); - throw std::invalid_argument{"Chunk Biome is None"}; + case PLAIN: + return plain.height_range; + case FOREST: + return forest.height_range; + case DESERT: + return desert.height_range; + case MOUNTAIN: + return mountain.height_range; + case NONE: + ASSERT_MSG(false, "Chunk Biome is None"); + throw std::invalid_argument{"Chunk Biome is None"}; } Logger::warn("Unknown Biome"); return {62, 4}; @@ -148,71 +138,61 @@ BiomeHeightRange get_biome_height_range(Biome biome) { Biome safe_int_to_biome(int x) { using enum Biome; - static const std::unordered_map INT_TO_BIOME_MAP { - {0, PLAIN}, - {1, FOREST}, - {2, DESERT}, - {3, MOUNTAIN} - }; + static const std::unordered_map INT_TO_BIOME_MAP{ + {0, PLAIN}, {1, FOREST}, {2, DESERT}, {3, MOUNTAIN}}; auto it = INT_TO_BIOME_MAP.find(x); - ASSERT_MSG(it != INT_TO_BIOME_MAP.end(), ":Can't Find"); + ASSERT_MSG(it != INT_TO_BIOME_MAP.end(), ":Can't Find"); return it->second; } -int get_interpolated_height(float world_x, float world_z, float temp, float humid) { - +int get_interpolated_height(float world_x, float world_z, float temp, + float humid) { + auto weight = [](float t, float h, float ct, float ch) -> float { float dt = t - ct; float dh = h - ch; - float dist = std::sqrt(dt*dt + dh*dh); - return std::max(0.0f, 0.5f - dist); + float dist = std::sqrt(dt * dt + dh * dh); + return std::max(0.0f, 0.5f - dist); }; float w_mountain = weight(temp, humid, 0.25f, 0.15f); - float w_plain = weight(temp, humid, 0.50f, 0.40f); - float w_desert = weight(temp, humid, 0.75f, 0.15f); - float w_forest = weight(temp, humid, 0.75f, 0.75f); + float w_plain = weight(temp, humid, 0.50f, 0.40f); + float w_desert = weight(temp, humid, 0.75f, 0.15f); + float w_forest = weight(temp, humid, 0.75f, 0.75f); // adjust transitions between chunks float pow_n = 8.0f; // the larger n is, the purer the biome w_mountain = std::pow(w_mountain, pow_n) * MOUNTAIN_FREQ; - w_plain = std::pow(w_plain, pow_n) * PLAIN_FREQ; - w_desert = std::pow(w_desert, pow_n) * DESERT_FREQ; - w_forest = std::pow(w_forest, pow_n) * FOREST_FREQ; + w_plain = std::pow(w_plain, pow_n) * PLAIN_FREQ; + w_desert = std::pow(w_desert, pow_n) * DESERT_FREQ; + w_forest = std::pow(w_forest, pow_n) * FOREST_FREQ; float total = w_mountain + w_plain + w_desert + w_forest; - w_mountain /= total; w_plain /= total; w_desert /= total; w_forest /= total; + w_mountain /= total; + w_plain /= total; + w_desert /= total; + w_forest /= total; auto sample_height = [&](Biome b) -> float { auto range = get_biome_height_range(b); auto [f1, f2, f3] = get_noise_frequencies_for_biome(b); - float n = - 1.00f * PerlinNoise::noise(world_x * f1, 0.5f, world_z * f1) + - 0.50f * PerlinNoise::noise(world_x * f2, 0.5f, world_z * f2) + - 0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3); + float n = 1.00f * PerlinNoise::noise(world_x * f1, 0.5f, world_z * f1) + + 0.50f * PerlinNoise::noise(world_x * f2, 0.5f, world_z * f2) + + 0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3); n /= 1.75f; return range.base_y + n * range.amplitude; }; - float h = w_mountain * sample_height(Biome::MOUNTAIN) - + w_plain * sample_height(Biome::PLAIN) - + w_desert * sample_height(Biome::DESERT) - + w_forest * sample_height(Biome::FOREST); + float h = w_mountain * sample_height(Biome::MOUNTAIN) + + w_plain * sample_height(Biome::PLAIN) + + w_desert * sample_height(Biome::DESERT) + + w_forest * sample_height(Biome::FOREST); return static_cast(h); } -PlainParams& plain_params() { - return plain; -} -ForestParams& forest_params() { - return forest; -} -DesertParams& desert_params() { - return desert; -} -MountainParams& mountain_params() { - return mountain; -} - -} +PlainParams& plain_params() { return plain; } +ForestParams& forest_params() { return forest; } +DesertParams& desert_params() { return desert; } +MountainParams& mountain_params() { return mountain; } +} // namespace Cubed diff --git a/src/gameplay/chunk.cpp b/src/gameplay/chunk.cpp index dd60995..a5f5eb7 100644 --- a/src/gameplay/chunk.cpp +++ b/src/gameplay/chunk.cpp @@ -1,47 +1,37 @@ -#include -#include -#include -#include -#include -#include -#include +#include "Cubed/gameplay/chunk.hpp" + +#include "Cubed/gameplay/world.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/log.hpp" #include namespace Cubed { -Chunk::Chunk(World& world, ChunkPos chunk_pos) : - m_chunk_pos(chunk_pos), - m_world(world) -{ - -} +Chunk::Chunk(World& world, ChunkPos chunk_pos) + : m_chunk_pos(chunk_pos), m_world(world) {} Chunk::~Chunk() { if (m_vbo != 0) { m_world.push_delete_vbo(m_vbo); } - } -Chunk::Chunk(Chunk&& other) noexcept : - m_dirty(other.is_dirty()), - m_need_upload(other.m_need_upload.load()), - m_is_on_gen_vertex_data(other.m_is_on_gen_vertex_data.load()), - m_vertex_sum(other.m_vertex_sum.load()), - m_biome(other.m_biome.load()), - m_chunk_pos(std::move(other.m_chunk_pos)), - m_world(other.m_world), - m_heightmap(std::move(other.m_heightmap)), - m_blocks(std::move(other.m_blocks)), - m_vbo(other.m_vbo), - m_vertexs_data(std::move(other.m_vertexs_data)) -{ +Chunk::Chunk(Chunk&& other) noexcept + : m_dirty(other.is_dirty()), m_need_upload(other.m_need_upload.load()), + m_is_on_gen_vertex_data(other.m_is_on_gen_vertex_data.load()), + m_vertex_sum(other.m_vertex_sum.load()), m_biome(other.m_biome.load()), + m_chunk_pos(std::move(other.m_chunk_pos)), m_world(other.m_world), + m_heightmap(std::move(other.m_heightmap)), + m_blocks(std::move(other.m_blocks)), m_vbo(other.m_vbo), + m_vertexs_data(std::move(other.m_vertexs_data)) { other.m_vbo = 0; } Chunk& Chunk::operator=(Chunk&& other) noexcept { - //Logger::info("other Chunk pos {} {} in Chunk& Chunk::operator=(Chunk&& other) this {}", other.m_chunk_pos.x, other.m_chunk_pos.z, static_cast(&other)); + // Logger::info("other Chunk pos {} {} in Chunk& Chunk::operator=(Chunk&& + // other) this {}", other.m_chunk_pos.x, other.m_chunk_pos.z, + // static_cast(&other)); m_vbo = other.m_vbo; other.m_vbo = 0; m_chunk_pos = std::move(other.m_chunk_pos); @@ -56,26 +46,24 @@ Chunk& Chunk::operator=(Chunk&& other) noexcept { return *this; } -Biome Chunk::get_biome() const { - return m_biome.load(); -} +Biome Chunk::get_biome() const { return m_biome.load(); } -ChunkPos Chunk::get_chunk_pos() const { - return m_chunk_pos; -} +ChunkPos Chunk::get_chunk_pos() const { return m_chunk_pos; } -const std::vector& Chunk::get_chunk_blocks() const{ - return m_blocks; -} +const std::vector& Chunk::get_chunk_blocks() const { return m_blocks; } HeightMapArray Chunk::get_heightmap() const { - //Logger::info("Chunk pos {} {} in get_heightmap this {}", m_chunk_pos.x, m_chunk_pos.z, static_cast(this)); + // Logger::info("Chunk pos {} {} in get_heightmap this {}", m_chunk_pos.x, + // m_chunk_pos.z, static_cast(this)); return m_heightmap; } int Chunk::get_index(int x, int y, int z) { - ASSERT(!(x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE)); - if ((x * WORLD_SIZE_Y + y) * CHUCK_SIZE + z < 0 || (x * WORLD_SIZE_Y + y) * CHUCK_SIZE + z >= CHUCK_SIZE * CHUCK_SIZE * WORLD_SIZE_Y) { + ASSERT(!(x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || + z >= CHUCK_SIZE)); + if ((x * WORLD_SIZE_Y + y) * CHUCK_SIZE + z < 0 || + (x * WORLD_SIZE_Y + y) * CHUCK_SIZE + z >= + CHUCK_SIZE * CHUCK_SIZE * WORLD_SIZE_Y) { Logger::error("block pos x {} y {} z {} range error", x, y, z); ASSERT(0); } @@ -86,17 +74,17 @@ int Chunk::get_index(const glm::vec3& pos) { return Chunk::get_index(pos.x, pos.y, pos.z); } -void Chunk::gen_vertex_data(const std::array*, 4>& neighbor_block) { +void Chunk::gen_vertex_data( + const std::array*, 4>& neighbor_block) { if (m_is_on_gen_vertex_data) { return; } m_is_on_gen_vertex_data = true; std::lock_guard lk(m_vertexs_data_mutex); m_vertexs_data.clear(); - - static const glm::ivec3 DIR[6] = { - {0,0,1},{1,0,0},{0,0,-1},{-1,0,0},{0,1,0},{0,-1,0} - }; + + static const glm::ivec3 DIR[6] = {{0, 0, 1}, {1, 0, 0}, {0, 0, -1}, + {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}}; for (int x = 0; x < SIZE_X; x++) { for (int y = 0; y < SIZE_Y; y++) { @@ -109,51 +97,57 @@ void Chunk::gen_vertex_data(const std::array*, 4>& ne if (cur_id == 0) { continue; } - + for (int face = 0; face < 6; face++) { int nx = x + DIR[face].x; int ny = y + DIR[face].y; int nz = z + DIR[face].z; bool neighbor_cull = false; - if (nx < 0 || nx >= SIZE_X || ny < 0 || ny >= SIZE_Y || nz < 0 || nz>= SIZE_Z) { - + if (nx < 0 || nx >= SIZE_X || ny < 0 || ny >= SIZE_Y || + nz < 0 || nz >= SIZE_Z) { + int world_nx = world_x + DIR[face].x; int world_ny = world_y + DIR[face].y; int world_nz = world_z + DIR[face].z; - auto [neighbor_x, neighbor_z] = World::chunk_pos(world_nx, world_nz); - - auto is_cull = [&](const std::vector* chunk_blocks){ - if (chunk_blocks == nullptr) { - return false; - } - int x, y, z; - y = world_ny; - x = world_nx - neighbor_x * CHUCK_SIZE; - z = world_nz - neighbor_z * CHUCK_SIZE; - if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) { - return false; - } - - int idx = Chunk::get_index(x, y, z); - // not init - if (static_cast(idx) >= chunk_blocks->size()) { - Logger::warn("not init"); - return false; - } - auto id = (*chunk_blocks)[idx]; - if (is_in_transparent_map(id)) { - if (id == cur_id) { - return true; - } else { + auto [neighbor_x, neighbor_z] = + World::chunk_pos(world_nx, world_nz); + + auto is_cull = + [&](const std::vector* chunk_blocks) { + if (chunk_blocks == nullptr) { return false; } - - } else { - return true; - } - }; + int x, y, z; + y = world_ny; + x = world_nx - neighbor_x * CHUCK_SIZE; + z = world_nz - neighbor_z * CHUCK_SIZE; + if (x < 0 || y < 0 || z < 0 || + x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || + z >= CHUCK_SIZE) { + return false; + } + + int idx = Chunk::get_index(x, y, z); + // not init + if (static_cast(idx) >= + chunk_blocks->size()) { + Logger::warn("not init"); + return false; + } + auto id = (*chunk_blocks)[idx]; + if (is_in_transparent_map(id)) { + if (id == cur_id) { + return true; + } else { + return false; + } + + } else { + return true; + } + }; if (m_chunk_pos.x + 1 == neighbor_x) { neighbor_cull = is_cull(neighbor_block[0]); @@ -164,7 +158,8 @@ void Chunk::gen_vertex_data(const std::array*, 4>& ne } else if (m_chunk_pos.z - 1 == neighbor_z) { neighbor_cull = is_cull(neighbor_block[3]); } - //neighbor_cull = m_world.is_block(glm::ivec3(world_x, world_y, world_z) + DIR[face]); + // neighbor_cull = m_world.is_block(glm::ivec3(world_x, + // world_y, world_z) + DIR[face]); } else { auto id = m_blocks[get_index(nx, ny, nz)]; if (!is_in_transparent_map(id)) { @@ -188,14 +183,13 @@ void Chunk::gen_vertex_data(const std::array*, 4>& ne VERTICES_POS[face][i][2] + (float)world_z * 1.0f, TEX_COORDS[face][i][0], TEX_COORDS[face][i][1], - static_cast(cur_id * 6 + face) + static_cast(cur_id * 6 + face) }; m_vertexs_data.emplace_back(vex); - } + } } } - } } m_vertex_sum = m_vertexs_data.size(); @@ -203,9 +197,7 @@ void Chunk::gen_vertex_data(const std::array*, 4>& ne m_is_on_gen_vertex_data = false; } -GLuint Chunk::get_vbo() const{ - return m_vbo; -} +GLuint Chunk::get_vbo() const { return m_vbo; } size_t Chunk::get_vertex_sum() const { if (m_vertex_sum == 0) { @@ -214,12 +206,11 @@ size_t Chunk::get_vertex_sum() const { return m_vertex_sum.load(); } - void Chunk::gen_phase_one() { m_generator = std::make_unique(*this); if (!m_generator) { Logger::error("ChunkGenerator is Nullptr"); - return; + return; } m_generator->assign_chunk_biome(); } @@ -227,7 +218,7 @@ void Chunk::gen_phase_one() { void Chunk::gen_phase_two(const std::array& adj_chunks) { if (!m_generator) { Logger::error("ChunkGenerator is Nullptr"); - return; + return; } m_generator->resolve_biome_adjacency_conflict(adj_chunks); } @@ -235,15 +226,16 @@ void Chunk::gen_phase_two(const std::array& adj_chunks) { void Chunk::gen_phase_three() { if (!m_generator) { Logger::error("ChunkGenerator is Nullptr"); - return; + return; } m_generator->generate_heightmap(); } -void Chunk::gen_phase_four(const std::array, 4>& neighbor_heightmap) { +void Chunk::gen_phase_four( + const std::array, 4>& neighbor_heightmap) { if (!m_generator) { Logger::error("ChunkGenerator is Nullptr"); - return; + return; } m_generator->blend_heightmap_boundaries(neighbor_heightmap); } @@ -251,15 +243,16 @@ void Chunk::gen_phase_four(const std::array, 4>& n void Chunk::gen_phase_five() { if (!m_generator) { Logger::error("ChunkGenerator is Nullptr"); - return; + return; } m_generator->generate_terrain_blocks(); } -void Chunk::gen_phase_six(const std::array>, 4>& neighbor_block) { +void Chunk::gen_phase_six( + const std::array>, 4>& neighbor_block) { if (!m_generator) { Logger::error("ChunkGenerator is Nullptr"); - return; + return; } m_generator->blend_surface_blocks_borders(neighbor_block); } @@ -267,7 +260,7 @@ void Chunk::gen_phase_six(const std::array>, void Chunk::gen_phase_seven() { if (!m_generator) { Logger::error("ChunkGenerator is Nullptr"); - return; + return; } m_generator->generate_vegetation(); mark_dirty(); @@ -278,58 +271,39 @@ void Chunk::upload_to_gpu() { ASSERT(is_need_upload()); if (m_vbo == 0) { - glGenBuffers(1, &m_vbo); + glGenBuffers(1, &m_vbo); } std::lock_guard lk(m_vertexs_data_mutex); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); - glBufferData(GL_ARRAY_BUFFER, m_vertexs_data.size() * sizeof(Vertex), m_vertexs_data.data(), GL_DYNAMIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, m_vertexs_data.size() * sizeof(Vertex), + m_vertexs_data.data(), GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // after fininshed it, can use clear_dirty(); m_need_upload = false; } -bool Chunk::is_dirty() const{ - return m_dirty.load(); -} +bool Chunk::is_dirty() const { return m_dirty.load(); } -void Chunk::mark_dirty() { - m_dirty = true; -} +void Chunk::mark_dirty() { m_dirty = true; } -void Chunk::clear_dirty() { - m_dirty = false; -} +void Chunk::clear_dirty() { m_dirty = false; } -bool Chunk::is_need_upload() const { - return m_need_upload.load(); -} +bool Chunk::is_need_upload() const { return m_need_upload.load(); } -void Chunk::need_upload() { - m_need_upload = true; -} +void Chunk::need_upload() { m_need_upload = true; } -void Chunk::set_chunk_block(int index ,unsigned id) { +void Chunk::set_chunk_block(int index, unsigned id) { m_blocks[index] = id; mark_dirty(); } -ChunkPos Chunk::chunk_pos() const{ - return m_chunk_pos; -} +ChunkPos Chunk::chunk_pos() const { return m_chunk_pos; } -Biome Chunk::biome() const{ - return m_biome; -} +Biome Chunk::biome() const { return m_biome; } -void Chunk::biome(Biome b) { - m_biome = b; -} +void Chunk::biome(Biome b) { m_biome = b; } -HeightMapArray& Chunk::heightmap() { - return m_heightmap; -} -std::vector& Chunk::blocks() { - return m_blocks; -} -} +HeightMapArray& Chunk::heightmap() { return m_heightmap; } +std::vector& Chunk::blocks() { return m_blocks; } +} // namespace Cubed diff --git a/src/gameplay/chunk_generator.cpp b/src/gameplay/chunk_generator.cpp index 8565d25..2d0d160 100644 --- a/src/gameplay/chunk_generator.cpp +++ b/src/gameplay/chunk_generator.cpp @@ -1,16 +1,14 @@ -#include +#include "Cubed/gameplay/chunk_generator.hpp" -#include -#include -#include -#include +#include "Cubed/gameplay/chunk.hpp" +#include "Cubed/gameplay/tree.hpp" +#include "Cubed/tools/cubed_hash.hpp" +#include "Cubed/tools/perlin_noise.hpp" #include namespace Cubed { -ChunkGenerator::ChunkGenerator(Chunk& chunk) : - m_chunk(chunk) -{ +ChunkGenerator::ChunkGenerator(Chunk& chunk) : m_chunk(chunk) { ASSERT_MSG(is_init, "ChunksGenerator is not init"); ChunkPos pos = m_chunk.get_chunk_pos(); unsigned seed = HASH::mix_hash(pos.x, pos.z, m_generator_seed); @@ -33,26 +31,26 @@ void ChunkGenerator::reload() { is_seed_change = false; } -const unsigned& ChunkGenerator::seed() { - return m_generator_seed; -} +const unsigned& ChunkGenerator::seed() { return m_generator_seed; } void ChunkGenerator::seed(unsigned s) { is_seed_change = true; m_generator_seed = s; } - void ChunkGenerator::assign_chunk_biome() { auto m_chunk_pos = m_chunk.chunk_pos(); float x = static_cast(m_chunk_pos.x); float z = static_cast(m_chunk_pos.z); - float temp = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 0.0f, z * BIOME_NOISE_FREQUENCY); - float humid = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 1.0f, z * BIOME_NOISE_FREQUENCY); + float temp = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 0.0f, + z * BIOME_NOISE_FREQUENCY); + float humid = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 1.0f, + z * BIOME_NOISE_FREQUENCY); auto biome = get_biome_from_noise(temp, humid); m_chunk.biome(biome); } -void ChunkGenerator::resolve_biome_adjacency_conflict(const std::array& adj_chunks) { +void ChunkGenerator::resolve_biome_adjacency_conflict( + const std::array& adj_chunks) { auto m_biome = m_chunk.biome(); for (auto& chunk : adj_chunks) { if (chunk == nullptr) { @@ -75,33 +73,36 @@ void ChunkGenerator::resolve_biome_adjacency_conflict(const std::array(x + m_chunk_pos.x * CHUCK_SIZE); float world_z = static_cast(z + m_chunk_pos.z * CHUCK_SIZE); auto sample_height = [&](Biome b) -> float { auto range = get_biome_height_range(b); auto [f1, f2, f3] = get_noise_frequencies_for_biome(b); - float n = - 1.00f * PerlinNoise::noise(world_x * f1, 0.5f, world_z * f1) + - 0.50f * PerlinNoise::noise(world_x * f2, 0.5f, world_z * f2) + - 0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3); + float n = 1.00f * PerlinNoise::noise(world_x * f1, 0.5f, + world_z * f1) + + 0.50f * PerlinNoise::noise(world_x * f2, 0.5f, + world_z * f2) + + 0.25f * PerlinNoise::noise(world_x * f3, 0.5f, + world_z * f3); n /= 1.75f; return range.base_y + n * range.amplitude; }; - m_heightmap[x][z] = sample_height(m_biome); + m_heightmap[x][z] = sample_height(m_biome); } } } -void ChunkGenerator::blend_heightmap_boundaries(const std::array, 4>& neighbor_heightmap) { +void ChunkGenerator::blend_heightmap_boundaries( + const std::array, 4>& neighbor_heightmap) { auto& m_heightmap = m_chunk.heightmap(); // Width of interpolation influence (in number of cells) @@ -119,8 +120,11 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array((*neighbor_heightmap[0])[0][z]); - float t = 1.0f - static_cast(dist) / BLEND_RADIUS; // larger weight when closer + float neighbor_h = + static_cast((*neighbor_heightmap[0])[0][z]); + float t = + 1.0f - static_cast(dist) / + BLEND_RADIUS; // larger weight when closer // Use smoothstep for a more natural transition t = t * t * (3.0f - 2.0f * t); blended += t * neighbor_h; @@ -132,7 +136,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array((*neighbor_heightmap[1])[SIZE_X - 1][z]); + float neighbor_h = static_cast( + (*neighbor_heightmap[1])[SIZE_X - 1][z]); float t = 1.0f - static_cast(dist) / BLEND_RADIUS; t = t * t * (3.0f - 2.0f * t); blended += t * neighbor_h; @@ -144,7 +149,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array((*neighbor_heightmap[2])[x][0]); + float neighbor_h = + static_cast((*neighbor_heightmap[2])[x][0]); float t = 1.0f - static_cast(dist) / BLEND_RADIUS; t = t * t * (3.0f - 2.0f * t); blended += t * neighbor_h; @@ -156,7 +162,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array((*neighbor_heightmap[3])[x][SIZE_Z - 1]); + float neighbor_h = static_cast( + (*neighbor_heightmap[3])[x][SIZE_Z - 1]); float t = 1.0f - static_cast(dist) / BLEND_RADIUS; t = t * t * (3.0f - 2.0f * t); blended += t * neighbor_h; @@ -196,7 +203,6 @@ void ChunkGenerator::generate_terrain_blocks() { } else { m_blocks[Chunk::get_index(x, y, z)] = 2; } - } if (height > 110) { m_blocks[Chunk::get_index(x, height - 1, z)] = 3; @@ -219,19 +225,24 @@ void ChunkGenerator::generate_terrain_blocks() { } } -void ChunkGenerator::blend_surface_blocks_borders(const std::array>, 4>& neighbor_block) { +void ChunkGenerator::blend_surface_blocks_borders( + const std::array>, 4>& neighbor_block) { auto& m_blocks = m_chunk.blocks(); auto& m_heightmap = m_chunk.heightmap(); - + constexpr int BLEND_RADIUS = 12; constexpr int WORLD_HEIGHT = WORLD_SIZE_Y; - // Helper lambda: get top block type from a neighbor's block data at (nx, nz) - auto get_top_block_from_neighbor = [&](const std::vector& blocks, int nx, int nz) -> uint8_t { + // Helper lambda: get top block type from a neighbor's block data at (nx, + // nz) + auto get_top_block_from_neighbor = [&](const std::vector& blocks, + int nx, int nz) -> uint8_t { // Search from topmost y downwards for the first non-zero block for (int y = WORLD_HEIGHT - 1; y >= 0; --y) { - int idx = Chunk::get_index(nx, y, nz); // linear index: y * area + z * size + x - if (idx >= 0 && idx < static_cast(blocks.size()) && blocks[idx] != 0) { + int idx = Chunk::get_index( + nx, y, nz); // linear index: y * area + z * size + x + if (idx >= 0 && idx < static_cast(blocks.size()) && + blocks[idx] != 0) { return blocks[idx]; } } @@ -247,7 +258,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array total weight std::unordered_map weights; @@ -259,7 +271,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array(dist) / BLEND_RADIUS; t = t * t * (3.0f - 2.0f * t); // smoothstep if (t > 0.0f) { - uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[0], 0, z); + uint8_t type_neighbor = + get_top_block_from_neighbor(*neighbor_block[0], 0, z); weights[type_neighbor] += t; } } @@ -270,7 +283,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array(dist) / BLEND_RADIUS; t = t * t * (3.0f - 2.0f * t); if (t > 0.0f) { - uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[1], CHUCK_SIZE - 1, z); + uint8_t type_neighbor = get_top_block_from_neighbor( + *neighbor_block[1], CHUCK_SIZE - 1, z); weights[type_neighbor] += t; } } @@ -281,7 +295,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array(dist) / BLEND_RADIUS; t = t * t * (3.0f - 2.0f * t); if (t > 0.0f) { - uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[2], x, 0); + uint8_t type_neighbor = + get_top_block_from_neighbor(*neighbor_block[2], x, 0); weights[type_neighbor] += t; } } @@ -292,7 +307,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array(dist) / BLEND_RADIUS; t = t * t * (3.0f - 2.0f * t); if (t > 0.0f) { - uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[3], x, CHUCK_SIZE - 1); + uint8_t type_neighbor = get_top_block_from_neighbor( + *neighbor_block[3], x, CHUCK_SIZE - 1); weights[type_neighbor] += t; } } @@ -337,14 +353,12 @@ void ChunkGenerator::generate_vegetation() { for (auto x : x_arr) { for (auto z : z_arr) { if (m_random.random_bool(forest_params().tree_frequency)) { - build_tree(m_chunk, {x, static_cast(m_heightmap[x][z]), z}); + build_tree(m_chunk, + {x, static_cast(m_heightmap[x][z]), z}); } - } } } } - - -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/gameplay/player.cpp b/src/gameplay/player.cpp index 4b0eb8d..c3bed54 100644 --- a/src/gameplay/player.cpp +++ b/src/gameplay/player.cpp @@ -1,67 +1,50 @@ -#include +#include "Cubed/gameplay/player.hpp" + +#include "Cubed/config.hpp" +#include "Cubed/debug_collector.hpp" +#include "Cubed/gameplay/world.hpp" +#include "Cubed/tools/log.hpp" -#include -#include -#include -#include -#include #include namespace Cubed { -Player::Player(World& world, const std::string& name) : - m_name(name), - m_world(world) -{ +Player::Player(World& world, const std::string& name) + : m_name(name), m_world(world) { hot_reload(); } -Player::~Player() { - -} +Player::~Player() {} AABB Player::get_aabb() const { float half_width = m_size.x / 2.0f; float half_depth = m_size.z / 2.0f; - glm::vec3 min{ - m_player_pos.x - half_width, - m_player_pos.y, - m_player_pos.z - half_depth - }; + glm::vec3 min{m_player_pos.x - half_width, m_player_pos.y, + m_player_pos.z - half_depth}; - glm::vec3 max { - m_player_pos.x + half_width, - m_player_pos.y + m_size.y, - m_player_pos.z + half_depth - }; + glm::vec3 max{m_player_pos.x + half_width, m_player_pos.y + m_size.y, + m_player_pos.z + half_depth}; return AABB{min, max}; - } -const glm::vec3& Player::get_front() const { - return m_front; -} +const glm::vec3& Player::get_front() const { return m_front; } -const Gait& Player::get_gait() const { - return m_gait; -} +const Gait& Player::get_gait() const { return m_gait; } const std::optional& Player::get_look_block_pos() const { return m_look_block; } -const glm::vec3& Player::get_player_pos() const { - return m_player_pos; -} +const glm::vec3& Player::get_player_pos() const { return m_player_pos; } -const MoveState& Player::get_move_state() const { - return m_move_state; -} +const MoveState& Player::get_move_state() const { return m_move_state; } -bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front, glm::ivec3& block_pos, glm::vec3& normal, float distance) { +bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front, + glm::ivec3& block_pos, glm::vec3& normal, + float distance) { glm::vec3 dir = glm::normalize(front); - //float step = 0.1f; + // float step = 0.1f; glm::ivec3 cur = glm::floor(start); int ix = cur.x; int iy = cur.y; @@ -72,7 +55,7 @@ bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front, glm::ivec3 int step_z = (dir.z > 0) ? 1 : ((dir.z < 0) ? -1 : 0); static const float INF = std::numeric_limits::infinity(); - + float t_delta_x = (dir.x != 0) ? std::fabs(1.0f / dir.x) : INF; float t_delta_y = (dir.y != 0) ? std::fabs(1.0f / dir.y) : INF; float t_delta_z = (dir.z != 0) ? std::fabs(1.0f / dir.z) : INF; @@ -126,8 +109,6 @@ bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front, glm::ivec3 normal = glm::vec3(0.0f, 0.0f, -step_z); iz += step_z; } - - } return false; } @@ -147,13 +128,11 @@ void Player::change_mode(GameMode mode) { void Player::hot_reload() { auto& config = Config::get(); - m_sensitivity = static_cast(config.get("player.mouse_sensitivity")); - + m_sensitivity = + static_cast(config.get("player.mouse_sensitivity")); } -void Player::set_player_pos(const glm::vec3& pos) { - m_player_pos = pos; -} +void Player::set_player_pos(const glm::vec3& pos) { m_player_pos = pos; } void Player::update(float delta_time) { @@ -162,108 +141,109 @@ void Player::update(float delta_time) { check_player_chunk_transition(); DebugCollector::get().report("player_pos", - std::format("x: {:.2f} y: {:.2f} z: {:.2f}", - m_player_pos.x, m_player_pos.y, m_player_pos.z - )); - - DebugCollector::get().report("speed", std::format("Speed: {:.2} m/s", m_xz_speed)); + std::format("x: {:.2f} y: {:.2f} z: {:.2f}", + m_player_pos.x, m_player_pos.y, + m_player_pos.z)); + + DebugCollector::get().report("speed", + std::format("Speed: {:.2} m/s", m_xz_speed)); } void Player::update_player_move_state(int key, int action) { - switch(key) { - case GLFW_KEY_W: - if (action == GLFW_PRESS) { - m_move_state.forward = true; + switch (key) { + case GLFW_KEY_W: + if (action == GLFW_PRESS) { + m_move_state.forward = true; + } + if (action == GLFW_RELEASE) { + m_move_state.forward = false; + if (m_game_mode != SPECTATOR) { + m_gait = Gait::WALK; } - if (action == GLFW_RELEASE) { - m_move_state.forward = false; - if (m_game_mode != SPECTATOR) { - m_gait = Gait::WALK; - } - - } - break; - case GLFW_KEY_S: - if (action == GLFW_PRESS) { - m_move_state.back = true; - } - if (action == GLFW_RELEASE) { - m_move_state.back = false; - } - break; - case GLFW_KEY_A: - if (action == GLFW_PRESS) { - m_move_state.left = true; - } - if (action == GLFW_RELEASE) { - m_move_state.left = false; - } - break; - case GLFW_KEY_D: - if (action == GLFW_PRESS) { - m_move_state.right = true; - } - if (action == GLFW_RELEASE) { - m_move_state.right = false; - } - break; - case GLFW_KEY_SPACE: - if (action == GLFW_PRESS) { - m_move_state.up = true; - if (space_on) { - if (m_game_mode == CREATIVE) { - is_fly = !is_fly ? true : false; - m_y_speed = 0.0f; - } - space_on = false; - space_on_time = 0.0f; - } else { - space_on = true; - } - } - if (action == GLFW_RELEASE) { - m_move_state.up = false; - } - break; - case GLFW_KEY_LEFT_SHIFT: - if (action == GLFW_PRESS) { - m_move_state.down = true; - } - if (action == GLFW_RELEASE) { - m_move_state.down = false; - } - break; - case GLFW_KEY_LEFT_CONTROL: - if (action == GLFW_PRESS) { - m_gait = Gait::RUN; - } - break; - case GLFW_KEY_F4: - if (action == GLFW_PRESS) { + } + break; + case GLFW_KEY_S: + if (action == GLFW_PRESS) { + m_move_state.back = true; + } + if (action == GLFW_RELEASE) { + m_move_state.back = false; + } + break; + case GLFW_KEY_A: + if (action == GLFW_PRESS) { + m_move_state.left = true; + } + if (action == GLFW_RELEASE) { + m_move_state.left = false; + } + break; + case GLFW_KEY_D: + if (action == GLFW_PRESS) { + m_move_state.right = true; + } + if (action == GLFW_RELEASE) { + m_move_state.right = false; + } + break; + case GLFW_KEY_SPACE: + if (action == GLFW_PRESS) { + m_move_state.up = true; + if (space_on) { if (m_game_mode == CREATIVE) { - change_mode(SPECTATOR); - } else { - change_mode(CREATIVE); + is_fly = !is_fly ? true : false; + m_y_speed = 0.0f; } + space_on = false; + space_on_time = 0.0f; + } else { + space_on = true; } - break; + } + if (action == GLFW_RELEASE) { + m_move_state.up = false; + } + break; + case GLFW_KEY_LEFT_SHIFT: + if (action == GLFW_PRESS) { + m_move_state.down = true; + } + if (action == GLFW_RELEASE) { + m_move_state.down = false; + } + break; + case GLFW_KEY_LEFT_CONTROL: + if (action == GLFW_PRESS) { + m_gait = Gait::RUN; + } + break; + case GLFW_KEY_F4: + if (action == GLFW_PRESS) { + if (m_game_mode == CREATIVE) { + change_mode(SPECTATOR); + } else { + change_mode(CREATIVE); + } + } + break; } } void Player::update_front_vec(float offset_x, float offset_y) { m_yaw += offset_x * m_sensitivity; m_pitch += offset_y * m_sensitivity; - - m_yaw = std::fmod(m_yaw, 360.0); - - if (m_pitch > 89.0f) m_pitch = 89.0f; - if (m_pitch < -89.0f) m_pitch = -89.0f; - + m_yaw = std::fmod(m_yaw, 360.0); + + if (m_pitch > 89.0f) + m_pitch = 89.0f; + if (m_pitch < -89.0f) + m_pitch = -89.0f; + m_front.x = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); m_front.y = sin(glm::radians(m_pitch)); m_front.z = -cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); - + m_front = glm::normalize(m_front); } @@ -276,10 +256,9 @@ void Player::check_player_chunk_transition() { if (chunk == nullptr) { DebugCollector::get().report("biome", "Biome: Unknown"); } else { - DebugCollector::get() - .report("biome", "Biome: " + get_biome_str(chunk->get_biome())); + DebugCollector::get().report( + "biome", "Biome: " + get_biome_str(chunk->get_biome())); } - } } @@ -291,15 +270,12 @@ void Player::update_direction() { glm::vec3 move_dir = glm::vec3(0.0f); if (m_move_state.forward) { move_dir_front += glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z)); - } if (m_move_state.back) { move_dir_front -= glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z)); - } if (m_move_state.left) { move_dir_right -= glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z)); - } if (m_move_state.right) { move_dir_right += glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z)); @@ -307,15 +283,17 @@ void Player::update_direction() { move_dir = move_dir_front + move_dir_right; if (glm::length(move_dir) > 0.001f) { - direction = glm::normalize(move_dir); + direction = glm::normalize(move_dir); } } void Player::update_lookup_block() { - // calculate the block that is looked + // calculate the block that is looked glm::ivec3 block_pos; glm::vec3 block_normal; - if(ray_cast(glm::vec3(m_player_pos.x, (m_player_pos.y + 1.6f), m_player_pos.z), m_front, block_pos, block_normal)) { + if (ray_cast( + glm::vec3(m_player_pos.x, (m_player_pos.y + 1.6f), m_player_pos.z), + m_front, block_pos, block_normal)) { m_look_block = LookBlock{block_pos, glm::floor(block_normal)}; } else { m_look_block = std::nullopt; @@ -325,25 +303,25 @@ void Player::update_lookup_block() { if (Input::get_input_state().mouse_state.left) { if (m_world.is_block(m_look_block->pos)) { m_world.set_block(m_look_block->pos, 0); - } Input::get_input_state().mouse_state.left = false; } if (Input::get_input_state().mouse_state.right) { glm::ivec3 near_pos = m_look_block->pos + m_look_block->normal; if (!m_world.is_block(near_pos)) { - auto x= near_pos.x; + auto x = near_pos.x; auto y = near_pos.y; auto z = near_pos.z; - AABB block_box = { - glm::vec3{static_cast(x), static_cast(y), static_cast(z)}, - glm::vec3{static_cast(x + 1), static_cast(y + 1), static_cast(z + 1)} - }; + AABB block_box = {glm::vec3{static_cast(x), + static_cast(y), + static_cast(z)}, + glm::vec3{static_cast(x + 1), + static_cast(y + 1), + static_cast(z + 1)}}; AABB player_box = get_aabb(); if (!player_box.intersects(block_box)) { m_world.set_block(near_pos, 1); } - } Input::get_input_state().mouse_state.right = false; } @@ -371,9 +349,10 @@ void Player::update_move(float delta_time) { space_on_time = 0.0f; } } - + // calculate speed - if (m_move_state.forward || m_move_state.back || m_move_state.left || m_move_state.right || m_move_state.up) { + if (m_move_state.forward || m_move_state.back || m_move_state.left || + m_move_state.right || m_move_state.up) { direction = glm::vec3(0.0f, 0.0f, 0.0f); m_xz_speed += m_acceleration * delta_time; if (m_xz_speed > m_max_speed) { @@ -389,11 +368,12 @@ void Player::update_move(float delta_time) { update_direction(); - move_distance = {direction.x * m_xz_speed * delta_time, 0.0f, direction.z * m_xz_speed * delta_time}; - + move_distance = {direction.x * m_xz_speed * delta_time, 0.0f, + direction.z * m_xz_speed * delta_time}; + if (is_fly) { if (m_move_state.up) { - m_y_speed = 7.5f; + m_y_speed = 7.5f; } if (m_move_state.down) { @@ -405,14 +385,13 @@ void Player::update_move(float delta_time) { } } else { if (m_move_state.up && can_up) { - m_y_speed = 7.5; - can_up = false; - + m_y_speed = 7.5; + can_up = false; } m_y_speed += -m_g * delta_time; } - + move_distance.y = m_y_speed * delta_time; // y update_y_move(); @@ -425,7 +404,6 @@ void Player::update_move(float delta_time) { Logger::warn("y is tow low"); m_player_pos += glm::vec3(1.0f, 100.0f, 1.0f); } - } void Player::update_x_move() { @@ -445,10 +423,12 @@ void Player::update_x_move() { for (int y = miny; y <= maxy; ++y) { for (int z = minz; z <= maxz; ++z) { if (m_world.is_block(glm::vec3{x, y, z})) { - AABB block_box = { - glm::vec3{static_cast(x), static_cast(y), static_cast(z)}, - glm::vec3{static_cast(x + 1), static_cast(y + 1), static_cast(z + 1)} - }; + AABB block_box = {glm::vec3{static_cast(x), + static_cast(y), + static_cast(z)}, + glm::vec3{static_cast(x + 1), + static_cast(y + 1), + static_cast(z + 1)}}; if (player_box.intersects(block_box)) { m_gait = Gait::WALK; m_player_pos.x -= move_distance.x; @@ -477,10 +457,12 @@ void Player::update_y_move() { for (int y = miny; y <= maxy; ++y) { for (int z = minz; z <= maxz; ++z) { if (m_world.is_block(glm::vec3{x, y, z})) { - AABB block_box = { - glm::vec3{static_cast(x), static_cast(y), static_cast(z)}, - glm::vec3{static_cast(x + 1), static_cast(y + 1), static_cast(z + 1)} - }; + AABB block_box = {glm::vec3{static_cast(x), + static_cast(y), + static_cast(z)}, + glm::vec3{static_cast(x + 1), + static_cast(y + 1), + static_cast(z + 1)}}; if (player_box.intersects(block_box)) { m_player_pos.y -= move_distance.y; m_y_speed = 0.0f; @@ -513,10 +495,12 @@ void Player::update_z_move() { for (int y = miny; y <= maxy; ++y) { for (int z = minz; z <= maxz; ++z) { if (m_world.is_block(glm::vec3{x, y, z})) { - AABB block_box = { - glm::vec3{static_cast(x), static_cast(y), static_cast(z)}, - glm::vec3{static_cast(x + 1), static_cast(y + 1), static_cast(z + 1)} - }; + AABB block_box = {glm::vec3{static_cast(x), + static_cast(y), + static_cast(z)}, + glm::vec3{static_cast(x + 1), + static_cast(y + 1), + static_cast(z + 1)}}; if (player_box.intersects(block_box)) { m_gait = Gait::WALK; m_player_pos.z -= move_distance.z; @@ -539,32 +523,16 @@ void Player::update_scroll(double yoffset) { m_max_speed -= 1.0f; } } - } + } } -float& Player::max_walk_speed() { - return m_max_walk_speed; -} -float& Player::max_run_speed() { - return m_max_run_speed; -} -float& Player::max_speed() { - return m_max_speed; -} -float& Player::acceleration() { - return m_acceleration; -} -float& Player::deceleration() { - return m_deceleration; -} -float& Player::g() { - return m_g; -} -Gait& Player::gait() { - return m_gait; -} -GameMode& Player::game_mode() { - return m_game_mode; -} +float& Player::max_walk_speed() { return m_max_walk_speed; } +float& Player::max_run_speed() { return m_max_run_speed; } +float& Player::max_speed() { return m_max_speed; } +float& Player::acceleration() { return m_acceleration; } +float& Player::deceleration() { return m_deceleration; } +float& Player::g() { return m_g; } +Gait& Player::gait() { return m_gait; } +GameMode& Player::game_mode() { return m_game_mode; } -} +} // namespace Cubed diff --git a/src/gameplay/tree.cpp b/src/gameplay/tree.cpp index 64a52d0..af2f4c6 100644 --- a/src/gameplay/tree.cpp +++ b/src/gameplay/tree.cpp @@ -1,96 +1,50 @@ -#include +#include "Cubed/gameplay/tree.hpp" -#include +#include "Cubed/gameplay/chunk.hpp" #include namespace Cubed { - using glm::ivec3; -static constexpr std::array TREE {{ - {{0, 1, 0}, 5}, - {{0, 2, 0}, 5}, - {{0, 3, 0}, 5}, - {{0, 4, 0}, 5}, - {{0, 5, 0}, 5}, - {{0, 6, 0}, 6}, - {{0, 5, 1}, 6}, - {{1, 5, 0}, 6}, - {{0, 5, -1}, 6}, - {{-1, 5, 0}, 6}, - {{1, 5, 1}, 6}, - {{1, 5, -1}, 6}, - {{-1, 5, -1}, 6}, - {{-1, 5, 1}, 6}, - {{0, 4, 1}, 6}, - {{1, 4, 0}, 6}, - {{0, 4, -1}, 6}, - {{-1, 4, 0}, 6}, - {{1, 4, 1}, 6}, - {{1, 4, -1}, 6}, - {{-1, 4, -1}, 6}, - {{-1, 4, 1}, 6}, - {{0, 4, 2}, 6}, - {{2, 4, 0}, 6}, - {{0, 4, -2}, 6}, - {{-2, 4, 0}, 6}, - {{2, 4, 2}, 6}, - {{2, 4, -2}, 6}, - {{-2, 4, -2}, 6}, - {{-2, 4, 2}, 6}, - {{1, 4, 2}, 6}, - {{2, 4, 1}, 6}, - {{-1, 4, 2}, 6}, - {{2, 4, -1}, 6}, - {{1, 4, -2}, 6}, - {{-2, 4, 1}, 6}, - {{-1, 4, -2}, 6}, - {{-2, 4, -1}, 6}, - {{0, 3, 1}, 6}, - {{1, 3, 0}, 6}, - {{0, 3, -1}, 6}, - {{-1, 3, 0}, 6}, - {{1, 3, 1}, 6}, - {{1, 3, -1}, 6}, - {{-1, 3, -1}, 6}, - {{-1, 3, 1}, 6}, - {{0, 3, 2}, 6}, - {{2, 3, 0}, 6}, - {{0, 3, -2}, 6}, - {{-2, 3, 0}, 6}, - {{2, 3, 2}, 6}, - {{2, 3, -2}, 6}, - {{-2, 3, -2}, 6}, - {{-2, 3, 2}, 6}, - {{1, 3, 2}, 6}, - {{2, 3, 1}, 6}, - {{-1, 3, 2}, 6}, - {{2, 3, -1}, 6}, - {{1, 3, -2}, 6}, - {{-2, 3, 1}, 6}, - {{-1, 3, -2}, 6}, - {{-2, 3, -1}, 6}, +static constexpr std::array TREE{{ + {{0, 1, 0}, 5}, {{0, 2, 0}, 5}, {{0, 3, 0}, 5}, {{0, 4, 0}, 5}, + {{0, 5, 0}, 5}, {{0, 6, 0}, 6}, {{0, 5, 1}, 6}, {{1, 5, 0}, 6}, + {{0, 5, -1}, 6}, {{-1, 5, 0}, 6}, {{1, 5, 1}, 6}, {{1, 5, -1}, 6}, + {{-1, 5, -1}, 6}, {{-1, 5, 1}, 6}, {{0, 4, 1}, 6}, {{1, 4, 0}, 6}, + {{0, 4, -1}, 6}, {{-1, 4, 0}, 6}, {{1, 4, 1}, 6}, {{1, 4, -1}, 6}, + {{-1, 4, -1}, 6}, {{-1, 4, 1}, 6}, {{0, 4, 2}, 6}, {{2, 4, 0}, 6}, + {{0, 4, -2}, 6}, {{-2, 4, 0}, 6}, {{2, 4, 2}, 6}, {{2, 4, -2}, 6}, + {{-2, 4, -2}, 6}, {{-2, 4, 2}, 6}, {{1, 4, 2}, 6}, {{2, 4, 1}, 6}, + {{-1, 4, 2}, 6}, {{2, 4, -1}, 6}, {{1, 4, -2}, 6}, {{-2, 4, 1}, 6}, + {{-1, 4, -2}, 6}, {{-2, 4, -1}, 6}, {{0, 3, 1}, 6}, {{1, 3, 0}, 6}, + {{0, 3, -1}, 6}, {{-1, 3, 0}, 6}, {{1, 3, 1}, 6}, {{1, 3, -1}, 6}, + {{-1, 3, -1}, 6}, {{-1, 3, 1}, 6}, {{0, 3, 2}, 6}, {{2, 3, 0}, 6}, + {{0, 3, -2}, 6}, {{-2, 3, 0}, 6}, {{2, 3, 2}, 6}, {{2, 3, -2}, 6}, + {{-2, 3, -2}, 6}, {{-2, 3, 2}, 6}, {{1, 3, 2}, 6}, {{2, 3, 1}, 6}, + {{-1, 3, 2}, 6}, {{2, 3, -1}, 6}, {{1, 3, -2}, 6}, {{-2, 3, 1}, 6}, + {{-1, 3, -2}, 6}, {{-2, 3, -1}, 6}, }}; bool build_tree(Chunk& chunk, const glm::ivec3& pos) { auto& block = chunk.get_chunk_blocks(); - + if (block[Chunk::get_index(pos)] != 1) { Logger::info("Root is not Grass Block"); return false; } for (const auto& d : TREE) { auto tree_node = pos + d.offset; - int x = tree_node.x; - int y = tree_node.y; - int z = tree_node.z; - if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) { - return false; - } - if (block[Chunk::get_index(tree_node)] != 0) { - return false; + int x = tree_node.x; + int y = tree_node.y; + int z = tree_node.z; + if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || + z >= CHUCK_SIZE) { + return false; + } + if (block[Chunk::get_index(tree_node)] != 0) { + return false; } } for (const auto& d : TREE) { @@ -100,4 +54,4 @@ bool build_tree(Chunk& chunk, const glm::ivec3& pos) { return true; } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/gameplay/world.cpp b/src/gameplay/world.cpp index b7cd755..62a8ecc 100644 --- a/src/gameplay/world.cpp +++ b/src/gameplay/world.cpp @@ -1,29 +1,24 @@ -#include +#include "Cubed/gameplay/world.hpp" -#include -#include -#include -#include -#include -#include -#include +#include "Cubed/config.hpp" +#include "Cubed/debug_collector.hpp" +#include "Cubed/gameplay/player.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/cubed_hash.hpp" +#include "Cubed/tools/math_tools.hpp" #include namespace Cubed { -static constexpr ChunkPos CHUNK_DIR[] { - {1, 0}, {-1, 0}, {0, 1}, {0, -1} - }; +static constexpr ChunkPos CHUNK_DIR[]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; struct ChunkRenderData { std::array*, 4> neighbor_block; Chunk* chunk; }; -World::World() { - -} +World::World() {} World::~World() { stop_gen_thread(); @@ -37,12 +32,10 @@ World::~World() { } } -bool World::can_move(const AABB& player_box) const{ +bool World::can_move(const AABB& player_box) const { return true; } - return true; -} - -const std::optional& World::get_look_block_pos(const std::string& name) const{ +const std::optional& +World::get_look_block_pos(const std::string& name) const { static std::optional null_look_block = std::nullopt; auto it = m_players.find(HASH::str(name)); if (it == m_players.end()) { @@ -52,7 +45,6 @@ const std::optional& World::get_look_block_pos(const std::string& nam } return it->second.get_look_block_pos(); - } const Chunk* World::get_chunk(const ChunkPos& pos) const { @@ -64,13 +56,13 @@ const Chunk* World::get_chunk(const ChunkPos& pos) const { return &it->second; } -Player& World::get_player(const std::string& name){ +Player& World::get_player(const std::string& name) { auto it = m_players.find(HASH::str(name)); if (it == m_players.end()) { Logger::error("Can't find player {}", name); ASSERT(0); } - + return it->second; } @@ -84,11 +76,12 @@ void World::init_world() { ChunkPos pos{ns, nt}; - m_chunks.emplace(pos, Chunk(*this, pos)); + m_chunks.emplace(pos, Chunk(*this, pos)); } } - Logger::info("Max Support Thread is {}", std::thread::hardware_concurrency()); + Logger::info("Max Support Thread is {}", + std::thread::hardware_concurrency()); init_chunks(); auto t2 = std::chrono::system_clock::now(); auto d = std::chrono::duration_cast(t2 - t1); @@ -108,20 +101,20 @@ void World::init_chunks() { chunk_ptrs.push_back(&chunk); } - std::for_each(std::execution::par, chunk_ptrs.begin(), chunk_ptrs.end(), [](auto& chunk){ - chunk->init_chunk(); + std::for_each(std::execution::par, chunk_ptrs.begin(), chunk_ptrs.end(), +[](auto& chunk){ chunk->init_chunk(); }); std::atomic sync{0}; sync.store(1, std::memory_order_release); sync.load(std::memory_order_acquire); - + std::vector pending_gen_data; pending_gen_data.reserve(m_chunks.size()); for (auto& [pos, chunk] : m_chunks) { ChunkRenderData data; data.chunk = &chunk; - for (int i = 0; i < 4; i++) { + for (int i = 0; i < 4; i++) { auto it = m_chunks.find(pos + CHUNK_DIR[i]); if (it != m_chunks.end()) { data.neighbor_block[i] = &(it->second.get_chunk_blocks()); @@ -131,16 +124,15 @@ void World::init_chunks() { } pending_gen_data.emplace_back(std::move(data)); } - std::for_each(std::execution::par, pending_gen_data.begin(), pending_gen_data.end(), [](ChunkRenderData& data){ - if(!data.chunk) { - return ; + std::for_each(std::execution::par, pending_gen_data.begin(), +pending_gen_data.end(), [](ChunkRenderData& data){ if(!data.chunk) { return ; } data.chunk->gen_vertex_data(data.neighbor_block); }); for (auto& chunk_map : m_chunks) { auto& [chunk_pos, chunk] = chunk_map; chunk.upload_to_gpu(); - + } } */ @@ -159,7 +151,6 @@ void World::init_chunks() { continue; } neighbor_chunks[i] = &it->second; - } chunks.gen_phase_two(neighbor_chunks); } @@ -177,13 +168,12 @@ void World::init_chunks() { continue; } neighbor_chunk_heightmap[i] = it->second.get_heightmap(); - } chunks.gen_phase_four(neighbor_chunk_heightmap); } for (auto& [pos, chunks] : m_chunks) { - chunks.gen_phase_five(); + chunks.gen_phase_five(); } std::array>, 4> neighbor_block; for (auto& [pos, chunks] : m_chunks) { @@ -195,23 +185,22 @@ void World::init_chunks() { continue; } neighbor_block[i] = it->second.get_chunk_blocks(); - } chunks.gen_phase_six(neighbor_block); } for (auto& [pos, chunks] : m_chunks) { - chunks.gen_phase_seven(); + chunks.gen_phase_seven(); } std::atomic sync{0}; sync.store(1, std::memory_order_release); sync.load(std::memory_order_acquire); - + std::vector pending_gen_data; pending_gen_data.reserve(m_chunks.size()); for (auto& [pos, chunk] : m_chunks) { ChunkRenderData data; data.chunk = &chunk; - for (int i = 0; i < 4; i++) { + for (int i = 0; i < 4; i++) { auto it = m_chunks.find(pos + CHUNK_DIR[i]); if (it != m_chunks.end()) { data.neighbor_block[i] = &(it->second.get_chunk_blocks()); @@ -221,30 +210,32 @@ void World::init_chunks() { } pending_gen_data.emplace_back(std::move(data)); } - std::for_each(std::execution::par, pending_gen_data.begin(), pending_gen_data.end(), [](ChunkRenderData& data){ - if(!data.chunk) { - return ; - } - data.chunk->gen_vertex_data(data.neighbor_block); - }); + std::for_each(std::execution::par, pending_gen_data.begin(), + pending_gen_data.end(), [](ChunkRenderData& data) { + if (!data.chunk) { + return; + } + data.chunk->gen_vertex_data(data.neighbor_block); + }); for (auto& chunk_map : m_chunks) { auto& [chunk_pos, chunk] = chunk_map; chunk.upload_to_gpu(); - } - } void World::render(const glm::mat4& mvp_matrix) { Math::extract_frustum_planes(mvp_matrix, m_planes); int rendered_sum = 0; for (const auto& snapshot : m_render_snapshots) { - + if (is_aabb_in_frustum(snapshot.center, snapshot.half_extents)) { glBindBuffer(GL_ARRAY_BUFFER, snapshot.vbo); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, s)); - glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, layer)); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), + (void*)0); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), + (void*)offsetof(Vertex, s)); + glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex), + (void*)offsetof(Vertex, layer)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); @@ -253,13 +244,10 @@ void World::render(const glm::mat4& mvp_matrix) { glDrawArrays(GL_TRIANGLES, 0, snapshot.vertex_count); glBindBuffer(GL_ARRAY_BUFFER, 0); rendered_sum++; - } - - } - DebugCollector::get().report("rendered_chunk", "Rendered Chunk: " + std::to_string(rendered_sum)); - + DebugCollector::get().report( + "rendered_chunk", "Rendered Chunk: " + std::to_string(rendered_sum)); } ChunkPos World::chunk_pos(int world_x, int world_z) { @@ -285,10 +273,10 @@ void World::gen_chunks_internal() { compute_required_chunks(required_chunks); ASSERT_MSG(!required_chunks.empty(), "required chunks is empty!!"); - + std::vector need_gen_chunks_pos; sync_and_collect_missing_chunks(need_gen_chunks_pos, required_chunks); - + Logger::info("New Gen Chunks Sum: {}", need_gen_chunks_pos.size()); if (need_gen_chunks_pos.empty()) { m_could_gen = true; @@ -300,12 +288,13 @@ void World::gen_chunks_internal() { for (auto& pos : need_gen_chunks_pos) { new_chunks.push_back({pos, Chunk(*this, pos)}); } - + ConstChunkMap new_chunks_neighbor; // affected neighbor ChunkPtrUpdateList affected_neighbor; - build_neighbor_context_for_new_chunks(new_chunks_neighbor, affected_neighbor,new_chunks); - + build_neighbor_context_for_new_chunks(new_chunks_neighbor, + affected_neighbor, new_chunks); + std::array*, 4> neighbor_block; // build new chunk, but the neighbor in m_chunks also need to re-build @@ -323,7 +312,6 @@ void World::gen_chunks_internal() { continue; } neighbor_chunks[i] = it->second; - } chunks.gen_phase_two(neighbor_chunks); } @@ -335,7 +323,7 @@ void World::gen_chunks_internal() { std::array, 4> neighbor_chunk_heightmap; for (auto& [pos, chunks] : new_chunks) { { - //std::lock_guard lk(m_chunks_mutex); + // std::lock_guard lk(m_chunks_mutex); for (int i = 0; i < 4; i++) { auto neighbor_pos = pos + CHUNK_DIR[i]; auto it = new_chunks_neighbor.find(neighbor_pos); @@ -355,7 +343,7 @@ void World::gen_chunks_internal() { std::array>, 4> neighbor_blocks_data; for (auto& [pos, chunks] : new_chunks) { { - //std::lock_guard lk(m_chunks_mutex); + // std::lock_guard lk(m_chunks_mutex); for (int i = 0; i < 4; i++) { auto neighbor_pos = pos + CHUNK_DIR[i]; auto it = new_chunks_neighbor.find(neighbor_pos); @@ -384,7 +372,8 @@ void World::gen_chunks_internal() { chunk.gen_vertex_data(neighbor_block); } m_chunk_gen_fraction = 0.7f; - build_neighbor_context_for_affected_neighbors(affected_neighbor, new_chunks_neighbor); + build_neighbor_context_for_affected_neighbors(affected_neighbor, + new_chunks_neighbor); m_chunk_gen_fraction = 0.8f; for (auto& [pos, chunk] : affected_neighbor) { for (int i = 0; i < 4; i++) { @@ -397,14 +386,13 @@ void World::gen_chunks_internal() { } chunk->gen_vertex_data(neighbor_block); chunk->need_upload(); - } + } m_chunk_gen_fraction = 0.9f; { std::lock_guard lk(m_new_chunk_queue_mutex); for (auto& x : new_chunks) { m_new_chunk_queue.emplace_back(std::move(x)); } - } m_chunk_gen_fraction = 1.0f; } @@ -417,11 +405,10 @@ void World::sync_player_pos(glm::vec3& player_pos) { void World::compute_required_chunks(ChunkPosSet& required_chunks) { glm::vec3 player_pos; sync_player_pos(player_pos); - + int x = std::floor(player_pos.x); int z = std::floor(player_pos.z); auto [chunk_x, chunk_z] = chunk_pos(x, z); - required_chunks.reserve(m_rendering_distance * m_rendering_distance); int half = m_rendering_distance / 2; @@ -432,17 +419,19 @@ void World::compute_required_chunks(ChunkPosSet& required_chunks) { } } -void World::sync_and_collect_missing_chunks(std::vector& need_gen_chunks_pos, const ChunkPosSet& required_chunks) { +void World::sync_and_collect_missing_chunks( + std::vector& need_gen_chunks_pos, + const ChunkPosSet& required_chunks) { std::lock_guard lk(m_chunks_mutex); - for (auto it = m_chunks.begin(); it != m_chunks.end(); ) { + for (auto it = m_chunks.begin(); it != m_chunks.end();) { if (required_chunks.find(it->first) == required_chunks.end()) { it = m_chunks.erase(it); } else { ++it; } } - - for (auto pos: required_chunks) { + + for (auto pos : required_chunks) { auto it = m_chunks.find(pos); if (it == m_chunks.end()) { need_gen_chunks_pos.push_back(pos); @@ -450,7 +439,9 @@ void World::sync_and_collect_missing_chunks(std::vector& need_gen_chun } } -void World::build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neighbor, ChunkPtrUpdateList& affected_neighbor,const ChunkUpdateList& new_chunks) { +void World::build_neighbor_context_for_new_chunks( + ConstChunkMap& new_chunks_neighbor, ChunkPtrUpdateList& affected_neighbor, + const ChunkUpdateList& new_chunks) { { std::lock_guard lk(m_chunks_mutex); for (auto& [pos, chunk] : new_chunks) { @@ -468,7 +459,8 @@ void World::build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neig } } -void World::build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList& affected_neighbor, ConstChunkMap& new_chunks_neighbor) { +void World::build_neighbor_context_for_affected_neighbors( + ChunkPtrUpdateList& affected_neighbor, ConstChunkMap& new_chunks_neighbor) { std::lock_guard lk(m_chunks_mutex); for (auto& [pos, chunk] : affected_neighbor) { for (auto& dir : CHUNK_DIR) { @@ -483,11 +475,11 @@ void World::build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList& af void World::start_gen_thread() { m_gen_running = true; Logger::info("Gen Thread Started"); - m_gen_thread = std::thread([this](){ + m_gen_thread = std::thread([this]() { while (m_gen_running) { std::unique_lock lk(m_gen_signal_mutex); - m_gen_cv.wait(lk, [this](){ + m_gen_cv.wait(lk, [this]() { return m_need_gen_chunk.load() || !m_gen_running; }); if (!m_gen_running) { @@ -520,12 +512,13 @@ void World::need_gen() { std::lock_guard lk(m_gen_player_pos_mutex); m_gen_player_pos = get_player("TestPlayer").get_player_pos(); } - + m_need_gen_chunk = true; m_gen_cv.notify_one(); } -bool World::is_aabb_in_frustum(const glm::vec3& center, const glm::vec3& half_extents) { +bool World::is_aabb_in_frustum(const glm::vec3& center, + const glm::vec3& half_extents) { for (const auto& plane : m_planes) { // distance float d = glm::dot(glm::vec3(plane), center) + plane.w; @@ -553,14 +546,14 @@ int World::get_block(const glm::ivec3& block_pos) const { y = block_pos.y; x = block_pos.x - chunk_x * CHUCK_SIZE; z = block_pos.z - chunk_z * CHUCK_SIZE; - if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) { + if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || + z >= CHUCK_SIZE) { return 0; } return chunk_blocks[Chunk::get_index(x, y, z)]; - } -bool World::is_block(const glm::ivec3& block_pos) const{ +bool World::is_block(const glm::ivec3& block_pos) const { auto [chunk_x, chunk_z] = chunk_pos(block_pos.x, block_pos.z); std::lock_guard lk(m_chunks_mutex); auto it = m_chunks.find(ChunkPos{chunk_x, chunk_z}); @@ -573,7 +566,8 @@ bool World::is_block(const glm::ivec3& block_pos) const{ y = block_pos.y; x = block_pos.x - chunk_x * CHUCK_SIZE; z = block_pos.z - chunk_z * CHUCK_SIZE; - if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) { + if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || + z >= CHUCK_SIZE) { return false; } auto id = chunk_blocks[Chunk::get_index(x, y, z)]; @@ -596,22 +590,22 @@ void World::set_block(const glm::ivec3& block_pos, unsigned id) { auto it = m_chunks.find(ChunkPos{chunk_x, chunk_z}); if (it == m_chunks.end()) { - return ; + return; } int x, y, z; y = world_y; x = world_x - chunk_x * CHUCK_SIZE; z = world_z - chunk_z * CHUCK_SIZE; - if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) { - return ; + if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || + z >= CHUCK_SIZE) { + return; } it->second.set_chunk_block(Chunk::get_index(x, y, z), id); static const glm::ivec3 NEIGHBOR_DIRS[] = { - {1, 0, 0}, {-1, 0, 0}, {0, 0, -1}, {0, 0, 1} - }; + {1, 0, 0}, {-1, 0, 0}, {0, 0, -1}, {0, 0, 1}}; for (const auto& dir : NEIGHBOR_DIRS) { glm::ivec3 neighbor = block_pos + dir; @@ -620,17 +614,14 @@ void World::set_block(const glm::ivec3& block_pos, unsigned id) { auto it = m_chunks.find({cx, cz}); if (it != m_chunks.end()) { it->second.mark_dirty(); - } } - - } void World::update(float delta_time) { for (auto& player : m_players) { player.second.update(delta_time); - } + } { std::lock_guard lk(m_delete_vbo_mutex); for (auto x : m_pending_delete_vbo) { @@ -652,10 +643,10 @@ void World::update(float delta_time) { } // unified compute vertex data before rendering - { + { std::lock_guard lk(m_chunks_mutex); bool consumed = false; - + for (auto& x : m_new_chunk) { m_chunks.insert_or_assign(x.first, std::move(x.second)); consumed = true; @@ -663,7 +654,7 @@ void World::update(float delta_time) { if (consumed) { m_could_gen = true; } - + m_render_snapshots.clear(); for (auto& [pos, chunk] : m_chunks) { if (chunk.is_dirty()) { @@ -684,15 +675,17 @@ void World::update(float delta_time) { if (chunk.is_need_upload()) { chunk.upload_to_gpu(); } - m_render_snapshots.push_back({ - chunk.get_vbo(), - chunk.get_vertex_sum(), - glm::vec3(static_cast(pos.x * CHUCK_SIZE) + static_cast(CHUCK_SIZE / 2), static_cast(WORLD_SIZE_Y/ 2), static_cast(pos.z * CHUCK_SIZE) + static_cast(CHUCK_SIZE / 2)), - glm::vec3(static_cast(CHUCK_SIZE / 2), static_cast(WORLD_SIZE_Y / 2), static_cast(CHUCK_SIZE / 2)) - } - ); + m_render_snapshots.push_back( + {chunk.get_vbo(), chunk.get_vertex_sum(), + glm::vec3(static_cast(pos.x * CHUCK_SIZE) + + static_cast(CHUCK_SIZE / 2), + static_cast(WORLD_SIZE_Y / 2), + static_cast(pos.z * CHUCK_SIZE) + + static_cast(CHUCK_SIZE / 2)), + glm::vec3(static_cast(CHUCK_SIZE / 2), + static_cast(WORLD_SIZE_Y / 2), + static_cast(CHUCK_SIZE / 2))}); } - } } } @@ -703,7 +696,7 @@ void World::push_delete_vbo(GLuint vbo) { } void World::hot_reload() { - auto & config = Config::get(); + auto& config = Config::get(); int dist = config.get("world.rendering_distance"); m_rendering_distance = dist <= MAX_DISTANCE ? dist : MAX_DISTANCE; need_gen(); @@ -715,7 +708,7 @@ void World::rebuild_world() { } m_is_rebuilding = true; stop_gen_thread(); - + { std::scoped_lock lk(m_chunks_mutex, m_new_chunk_queue_mutex); m_chunks.clear(); @@ -725,21 +718,16 @@ void World::rebuild_world() { ChunkGenerator::reload(); start_gen_thread(); need_gen(); - + m_is_rebuilding = false; - } -float World::chunk_gen_fraction() const { - return m_chunk_gen_fraction.load(); -} +float World::chunk_gen_fraction() const { return m_chunk_gen_fraction.load(); } -int World::rendering_distance() const { - return m_rendering_distance.load(); -} +int World::rendering_distance() const { return m_rendering_distance.load(); } void World::rendering_distance(int rendering_distance) { m_rendering_distance = rendering_distance; } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/input.cpp b/src/input.cpp index 1836a9e..5060d19 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -1,17 +1,13 @@ -#include -#include -namespace Cubed { +#include "Cubed/input.hpp" +namespace Cubed { static InputState input_state; namespace Input { - InputState& get_input_state() { - return input_state; - } - -} +InputState& get_input_state() { return input_state; } +} // namespace Input -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 54d1a9f..68dd1f2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,11 +1,9 @@ -#include +#include "Cubed/app.hpp" int main(int argc, char** argv) { - + static_assert(sizeof(int) == sizeof(int32_t)); static_assert(sizeof(unsigned int) == sizeof(uint32_t)); return Cubed::App::start_cubed_application(argc, argv); } - - diff --git a/src/map_table.cpp b/src/map_table.cpp index 00a5fd3..4a26837 100644 --- a/src/map_table.cpp +++ b/src/map_table.cpp @@ -1,17 +1,18 @@ -#include -#include -#include -#include +#include "Cubed/map_table.hpp" + +#include "Cubed/gameplay/block.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/cubed_hash.hpp" namespace Cubed { std::unordered_map MapTable::id_to_name_map; std::unordered_map MapTable::name_to_id_map; - const std::string& MapTable::get_name_from_id(unsigned id) { auto it = id_to_name_map.find(id); - ASSERT_MSG(it != id_to_name_map.end(), "Id: " + std::to_string(id) + " is not exist"); + ASSERT_MSG(it != id_to_name_map.end(), + "Id: " + std::to_string(id) + " is not exist"); return it->second; } unsigned MapTable::get_id_from_name(const std::string& name) { @@ -28,8 +29,6 @@ void MapTable::init_map() { id_to_name_map[i] = BLOCK_REISTER[i]; name_to_id_map[HASH::str(BLOCK_REISTER[i])] = i; } - -} - } +} // namespace Cubed diff --git a/src/renderer.cpp b/src/renderer.cpp index 9409d12..bd881a1 100644 --- a/src/renderer.cpp +++ b/src/renderer.cpp @@ -1,33 +1,28 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "Cubed/renderer.hpp" + +#include "Cubed/camera.hpp" +#include "Cubed/config.hpp" +#include "Cubed/debug_collector.hpp" +#include "Cubed/dev_panel.hpp" +#include "Cubed/gameplay/player.hpp" +#include "Cubed/gameplay/world.hpp" +#include "Cubed/primitive_data.hpp" +#include "Cubed/texture_manager.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/cubed_hash.hpp" +#include "Cubed/tools/font.hpp" +#include "Cubed/tools/log.hpp" +#include "Cubed/tools/shader_tools.hpp" #include -#include - #include +#include namespace Cubed { -Renderer::Renderer(const Camera& camera, World& world, const TextureManager& texture_manager, DevPanel& dev_panel): - m_camera(camera), - m_dev_panel(dev_panel), - m_texture_manager(texture_manager), - m_world(world) -{ - -} +Renderer::Renderer(const Camera& camera, World& world, + const TextureManager& texture_manager, DevPanel& dev_panel) + : m_camera(camera), m_dev_panel(dev_panel), + m_texture_manager(texture_manager), m_world(world) {} Renderer::~Renderer() { glBindBuffer(GL_ARRAY_BUFFER, 0); @@ -51,13 +46,19 @@ void Renderer::init() { exit(EXIT_FAILURE); } Logger::info("OpenGL Version: {}.{}", GLVersion.major, GLVersion.minor); - Logger::info("Renderer: {}", reinterpret_cast(glGetString(GL_RENDERER))); + Logger::info("Renderer: {}", + reinterpret_cast(glGetString(GL_RENDERER))); - Shader world_shader{"world", "shaders/block_v_shader.glsl", "shaders/block_f_shader.glsl"}; - Shader outline_shader{"outline", "shaders/outline_v_shader.glsl", "shaders/outline_f_shader.glsl"}; - Shader sky_shdaer{"sky", "shaders/sky_v_shader.glsl", "shaders/sky_f_shader.glsl"}; - Shader ui_shdaer{"ui", "shaders/ui_v_shader.glsl", "shaders/ui_f_shader.glsl"}; - Shader text_shdaer{"text", "shaders/text_v_shader.glsl", "shaders/text_f_shader.glsl"}; + Shader world_shader{"world", "shaders/block_v_shader.glsl", + "shaders/block_f_shader.glsl"}; + Shader outline_shader{"outline", "shaders/outline_v_shader.glsl", + "shaders/outline_f_shader.glsl"}; + Shader sky_shdaer{"sky", "shaders/sky_v_shader.glsl", + "shaders/sky_f_shader.glsl"}; + Shader ui_shdaer{"ui", "shaders/ui_v_shader.glsl", + "shaders/ui_f_shader.glsl"}; + Shader text_shdaer{"text", "shaders/text_v_shader.glsl", + "shaders/text_f_shader.glsl"}; m_shaders.insert({world_shader.hash(), std::move(world_shader)}); m_shaders.insert({outline_shader.hash(), std::move(outline_shader)}); @@ -70,13 +71,17 @@ void Renderer::init() { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - #ifdef DEBUG_MODE + +#ifdef DEBUG_MODE glEnable(GL_DEBUG_OUTPUT); - glDebugMessageCallback([](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* user_param) { - Logger::log(Logger::Level::DEBUG, std::source_location::current(),"GL Debug: {}", reinterpret_cast(message)); - }, nullptr); - #endif + glDebugMessageCallback( + [](GLenum source, GLenum type, GLuint id, GLenum severity, + GLsizei length, const GLchar* message, const void* user_param) { + Logger::log(Logger::Level::DEBUG, std::source_location::current(), + "GL Debug: {}", reinterpret_cast(message)); + }, + nullptr); +#endif m_vao.resize(NUM_VAO); glGenVertexArrays(NUM_VAO, m_vao.data()); @@ -88,30 +93,28 @@ void Renderer::init() { glGenBuffers(1, &m_outline_indices_vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_outline_indices_vbo); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(OUTLINE_CUBE_INDICES), OUTLINE_CUBE_INDICES, GL_STATIC_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(OUTLINE_CUBE_INDICES), + OUTLINE_CUBE_INDICES, GL_STATIC_DRAW); glGenBuffers(1, &m_sky_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_sky_vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES_POS), VERTICES_POS, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES_POS), VERTICES_POS, + GL_STATIC_DRAW); glGenBuffers(1, &m_ui_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo); for (int i = 0; i < 6; i++) { - Vertex2D vex { - SQUARE_VERTICES[i][0], - SQUARE_VERTICES[i][1], - SQUARE_TEXTURE_POS[i][0], - SQUARE_TEXTURE_POS[i][1], - 0 - }; + Vertex2D vex{SQUARE_VERTICES[i][0], SQUARE_VERTICES[i][1], + SQUARE_TEXTURE_POS[i][0], SQUARE_TEXTURE_POS[i][1], 0}; m_ui.emplace_back(vex); } - glBufferData(GL_ARRAY_BUFFER, m_ui.size() * sizeof(Vertex2D), m_ui.data(), GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, m_ui.size() * sizeof(Vertex2D), m_ui.data(), + GL_STATIC_DRAW); glGenBuffers(1, &m_text_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_text_vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(float)* 6 * 4, NULL, GL_DYNAMIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); init_text(); @@ -155,14 +158,15 @@ void Renderer::render_outline() { m_mv_loc = shader.loc("mv_matrix"); m_proj_loc = shader.loc("proj_matrix"); - + const auto& block_pos = m_world.get_look_block_pos("TestPlayer"); if (block_pos != std::nullopt) { - m_m_mat = glm::translate(glm::mat4(1.0f), glm::vec3(block_pos.value().pos)); + m_m_mat = + glm::translate(glm::mat4(1.0f), glm::vec3(block_pos.value().pos)); m_mv_mat = m_v_mat * m_m_mat; glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_mv_mat)); - glUniformMatrix4fv(m_proj_loc, 1 ,GL_FALSE, glm::value_ptr(m_p_mat)); + glUniformMatrix4fv(m_proj_loc, 1, GL_FALSE, glm::value_ptr(m_p_mat)); glBindBuffer(GL_ARRAY_BUFFER, m_outline_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); @@ -174,23 +178,23 @@ void Renderer::render_outline() { glLineWidth(4.0f); glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0); } - } void Renderer::render_sky() { - + const auto& shader = get_shader("sky"); shader.use(); m_mv_loc = shader.loc("mv_matrix"); m_proj_loc = shader.loc("proj_matrix"); - m_m_mat = glm::translate(glm::mat4(1.0f), m_camera.get_camera_pos() - glm::vec3(0.5f, 0.5f, 0.5f)); + m_m_mat = glm::translate(glm::mat4(1.0f), m_camera.get_camera_pos() - + glm::vec3(0.5f, 0.5f, 0.5f)); m_v_mat = m_camera.get_camera_lookat(); m_mv_mat = m_v_mat * m_m_mat; glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_mv_mat)); - glUniformMatrix4fv(m_proj_loc, 1 ,GL_FALSE, glm::value_ptr(m_p_mat)); + glUniformMatrix4fv(m_proj_loc, 1, GL_FALSE, glm::value_ptr(m_p_mat)); glBindBuffer(GL_ARRAY_BUFFER, m_sky_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); @@ -200,7 +204,6 @@ void Renderer::render_sky() { glDrawArrays(GL_TRIANGLES, 0, 36); glEnable(GL_DEPTH_TEST); - } void Renderer::render_text() { @@ -234,8 +237,10 @@ void Renderer::render_ui() { glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)0); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, s)); - glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, layer)); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), + (void*)offsetof(Vertex2D, s)); + glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), + (void*)offsetof(Vertex2D, layer)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); @@ -249,28 +254,28 @@ void Renderer::render_ui() { glBindBuffer(GL_ARRAY_BUFFER, 0); glEnable(GL_DEPTH_TEST); - } void Renderer::update_fov(float fov) { m_fov = fov; - m_p_mat = glm::perspective(glm::radians(fov), m_aspect, 0.1f, 1000.0f); + m_p_mat = glm::perspective(glm::radians(fov), m_aspect, 0.1f, 1000.0f); } void Renderer::update_proj_matrix(float aspect, float width, float height) { m_aspect = aspect; - m_p_mat = glm::perspective(glm::radians(m_fov), aspect, 0.1f, 1000.0f); + m_p_mat = glm::perspective(glm::radians(m_fov), aspect, 0.1f, 1000.0f); m_ui_proj = glm::ortho(0.0f, width, height, 0.0f, -1.0f, 1.0f); // scale and then translate - m_ui_m_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(width / 2.0f, height / 2.0f, 0.0)) * - glm::scale(glm::mat4(1.0f), glm::vec3(50.0f, 50.0f, 1.0f)); - + m_ui_m_matrix = + glm::translate(glm::mat4(1.0f), + glm::vec3(width / 2.0f, height / 2.0f, 0.0)) * + glm::scale(glm::mat4(1.0f), glm::vec3(50.0f, 50.0f, 1.0f)); } void Renderer::render_world() { const auto& shader = get_shader("world"); shader.use(); - + m_mv_loc = shader.loc("mv_matrix"); m_proj_loc = shader.loc("proj_matrix"); glActiveTexture(GL_TEXTURE0); @@ -278,9 +283,9 @@ void Renderer::render_world() { glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_manager.get_texture_array()); m_m_mat = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); m_v_mat = m_camera.get_camera_lookat(); - m_mv_mat = m_v_mat * m_m_mat; + m_mv_mat = m_v_mat * m_m_mat; glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_mv_mat)); - glUniformMatrix4fv(m_proj_loc, 1 ,GL_FALSE, glm::value_ptr(m_p_mat)); + glUniformMatrix4fv(m_proj_loc, 1, GL_FALSE, glm::value_ptr(m_p_mat)); m_mvp_mat = m_p_mat * m_mv_mat; m_world.render(m_mvp_mat); } @@ -291,4 +296,4 @@ void Renderer::render_dev_panel() { glEnable(GL_DEPTH_TEST); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/shader.cpp b/src/shader.cpp index 284da73..3c107f0 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -1,27 +1,24 @@ -#include -#include -#include -#include -#include +#include "Cubed/shader.hpp" + +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/cubed_hash.hpp" +#include "Cubed/tools/log.hpp" +#include "Cubed/tools/shader_tools.hpp" namespace Cubed { +Shader::Shader() {} -Shader::Shader() { - -} - -Shader::Shader(const std::string& name, const std::string& v_shader_path, const std::string& f_shader_path) { +Shader::Shader(const std::string& name, const std::string& v_shader_path, + const std::string& f_shader_path) { m_program = Tools::create_shader_program(v_shader_path, f_shader_path); m_name = name; m_hash = HASH::str(name); } -Shader::Shader(Shader&& shader) noexcept: - m_program(shader.m_program), - m_hash(shader.m_hash), - m_name(std::move(shader.m_name)) -{ +Shader::Shader(Shader&& shader) noexcept + : m_program(shader.m_program), m_hash(shader.m_hash), + m_name(std::move(shader.m_name)) { shader.m_hash = 0; shader.m_program = 0; } @@ -32,7 +29,7 @@ Shader::~Shader() { } } -Shader& Shader::operator=(Shader&& shader) noexcept{ +Shader& Shader::operator=(Shader&& shader) noexcept { m_hash = shader.m_hash; m_name = std::move(shader.m_name); m_program = shader.m_program; @@ -41,7 +38,8 @@ Shader& Shader::operator=(Shader&& shader) noexcept{ return *this; } -void Shader::create(const std::string& name, const std::string& v_shader_path, const std::string& f_shader_path) { +void Shader::create(const std::string& name, const std::string& v_shader_path, + const std::string& f_shader_path) { if (!m_program) { Logger::warn("Shader has already created !"); return; @@ -72,14 +70,13 @@ GLuint Shader::loc(const std::string& loc) const { const std::string& Shader::name() const { if (m_name == "-1") { Logger::warn("Shader has already created !"); - } return m_name; } -void Shader::use() const{ +void Shader::use() const { ASSERT_MSG(m_program, "Shader don't create !"); glUseProgram(m_program); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/texture_manager.cpp b/src/texture_manager.cpp index 75667fd..662ee85 100644 --- a/src/texture_manager.cpp +++ b/src/texture_manager.cpp @@ -1,19 +1,17 @@ -#include -#include -#include -#include -#include +#include "Cubed/texture_manager.hpp" + +#include "Cubed/config.hpp" +#include "Cubed/constants.hpp" +#include "Cubed/map_table.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/log.hpp" +#include "Cubed/tools/shader_tools.hpp" namespace Cubed { +TextureManager::TextureManager() {} -TextureManager::TextureManager() { - -} - -TextureManager::~TextureManager() { - delet_texture(); -} +TextureManager::~TextureManager() { delet_texture(); } void TextureManager::delet_texture() { glDeleteTextures(1, &m_texture_array); @@ -21,17 +19,13 @@ void TextureManager::delet_texture() { Logger::info("Successfully delete all texture"); } -GLuint TextureManager::get_block_status_array() const{ +GLuint TextureManager::get_block_status_array() const { return m_block_status_array; } -GLuint TextureManager::get_texture_array() const{ - return m_texture_array; -} +GLuint TextureManager::get_texture_array() const { return m_texture_array; } -GLuint TextureManager::get_ui_array() const{ - return m_ui_array; -} +GLuint TextureManager::get_ui_array() const { return m_ui_array; } void TextureManager::load_block_status(unsigned id) { @@ -40,12 +34,8 @@ void TextureManager::load_block_status(unsigned id) { unsigned char* image_data = nullptr; image_data = (Tools::load_image_data(path)); glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array); - glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, - 0 ,0, id, - 16, 16, 1, - GL_RGBA, GL_UNSIGNED_BYTE, - image_data - ); + glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id, 16, 16, 1, GL_RGBA, + GL_UNSIGNED_BYTE, image_data); Tools::delete_image_data(image_data); } @@ -65,20 +55,15 @@ void TextureManager::load_block_texture(unsigned id) { image_data[3] = (Tools::load_image_data(block_texture_path + "/left.png")); image_data[4] = (Tools::load_image_data(block_texture_path + "/top.png")); image_data[5] = (Tools::load_image_data(block_texture_path + "/base.png")); - + glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array); Tools::check_opengl_error(); for (int i = 0; i < 6; i++) { - glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, - 0, 0, id * 6 + i, - 16, 16, 1, - GL_RGBA, GL_UNSIGNED_BYTE, - image_data[i] - ); + glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id * 6 + i, 16, 16, 1, + GL_RGBA, GL_UNSIGNED_BYTE, image_data[i]); Tools::check_opengl_error(); Tools::delete_image_data(image_data[i]); } - } void TextureManager::load_ui_texture(unsigned id) { @@ -88,20 +73,16 @@ void TextureManager::load_ui_texture(unsigned id) { unsigned char* image_data = nullptr; image_data = (Tools::load_image_data(path)); glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array); - glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, - 0 ,0, id, - 16, 16, 1, - GL_RGBA, GL_UNSIGNED_BYTE, - image_data - ); + glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id, 16, 16, 1, GL_RGBA, + GL_UNSIGNED_BYTE, image_data); Tools::delete_image_data(image_data); - } void TextureManager::init_texture() { glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &m_max_aniso); if (m_max_aniso > 0.0f) { - Logger::info("Support anisotropic filtering max_aniso is {}", m_max_aniso); + Logger::info("Support anisotropic filtering max_aniso is {}", + m_max_aniso); } m_aniso = Config::get().get("texture.aniso"); m_aniso = std::min(static_cast(m_max_aniso), m_aniso); @@ -112,12 +93,8 @@ void TextureManager::init_texture() { Tools::check_opengl_error(); glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array); Tools::check_opengl_error(); - glTexImage3D(GL_TEXTURE_2D_ARRAY, - 0, GL_RGBA, - 16, 16, - MAX_BLOCK_NUM * 6, - 0, GL_RGBA, - GL_UNSIGNED_BYTE, nullptr); + glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_BLOCK_NUM * 6, 0, + GL_RGBA, GL_UNSIGNED_BYTE, nullptr); Tools::check_opengl_error(); for (int i = 0; i < MAX_BLOCK_NUM; i++) { load_block_texture(i); @@ -127,24 +104,22 @@ void TextureManager::init_texture() { Tools::check_opengl_error(); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); Tools::check_opengl_error(); - glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, + GL_LINEAR_MIPMAP_LINEAR); Tools::check_opengl_error(); glGenerateMipmap(GL_TEXTURE_2D_ARRAY); Tools::check_opengl_error(); if (m_aniso >= 1) { - glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, static_cast(m_aniso)); + glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, + static_cast(m_aniso)); } - + glGenTextures(1, &m_block_status_array); Tools::check_opengl_error(); glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array); Tools::check_opengl_error(); - glTexImage3D(GL_TEXTURE_2D_ARRAY, - 0, GL_RGBA, - 16, 16, - MAX_BLOCK_STATUS, - 0, GL_RGBA, - GL_UNSIGNED_BYTE, nullptr); + glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_BLOCK_STATUS, 0, + GL_RGBA, GL_UNSIGNED_BYTE, nullptr); Tools::check_opengl_error(); for (int i = 0; i < MAX_BLOCK_STATUS; i++) { load_block_status(i); @@ -154,25 +129,23 @@ void TextureManager::init_texture() { Tools::check_opengl_error(); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); Tools::check_opengl_error(); - glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, + GL_LINEAR_MIPMAP_LINEAR); Tools::check_opengl_error(); glGenerateMipmap(GL_TEXTURE_2D_ARRAY); Tools::check_opengl_error(); if (m_aniso >= 1) { - glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, static_cast(m_aniso)); + glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, + static_cast(m_aniso)); } - + glGenTextures(1, &m_ui_array); Tools::check_opengl_error(); glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array); Tools::check_opengl_error(); - glTexImage3D(GL_TEXTURE_2D_ARRAY, - 0, GL_RGBA, - 16, 16, - MAX_UI_NUM, - 0, GL_RGBA, - GL_UNSIGNED_BYTE, nullptr); + glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_UI_NUM, 0, + GL_RGBA, GL_UNSIGNED_BYTE, nullptr); Tools::check_opengl_error(); for (int i = 0; i < MAX_UI_NUM; i++) { load_ui_texture(i); @@ -180,9 +153,7 @@ void TextureManager::init_texture() { glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - - + glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } void TextureManager::update() { @@ -191,19 +162,15 @@ void TextureManager::update() { } } -void TextureManager::need_reload() { - m_need_reload = true; -} +void TextureManager::need_reload() { m_need_reload = true; } void TextureManager::hot_reload() { delet_texture(); - + init_texture(); m_need_reload = false; } -int TextureManager::max_aniso() const { - return static_cast(m_max_aniso); -} +int TextureManager::max_aniso() const { return static_cast(m_max_aniso); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/tools/cubed_random.cpp b/src/tools/cubed_random.cpp index f0f6a59..ae2b017 100644 --- a/src/tools/cubed_random.cpp +++ b/src/tools/cubed_random.cpp @@ -1,30 +1,23 @@ -#include - -#include +#include "Cubed/tools/cubed_random.hpp" +#include "Cubed/tools/log.hpp" namespace Cubed { -Random::Random() { - -} +Random::Random() {} bool Random::random_bool(double probability) { std::bernoulli_distribution dist(probability); return dist(m_engine); } -std::mt19937& Random::engine() { - return m_engine; -} +std::mt19937& Random::engine() { return m_engine; } -unsigned Random::seed() { - return m_seed; -} +unsigned Random::seed() { return m_seed; } void Random::init(unsigned seed) { m_seed = seed; m_engine.seed(seed); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/tools/font.cpp b/src/tools/font.cpp index 7166fe2..384f803 100644 --- a/src/tools/font.cpp +++ b/src/tools/font.cpp @@ -1,14 +1,14 @@ -#include -#include -#include -#include -#include +#include "Cubed/tools/font.hpp" + +#include "Cubed/constants.hpp" +#include "Cubed/shader.hpp" +#include "Cubed/tools/log.hpp" +#include "Cubed/tools/shader_tools.hpp" namespace fs = std::filesystem; namespace Cubed { - Font::Font() { if (FT_Init_FreeType(&m_ft)) { @@ -18,12 +18,12 @@ Font::Font() { Logger::error("FREETYPE: Failed to load font"); } - FT_Set_Pixel_Sizes(m_face, 0, 48); + FT_Set_Pixel_Sizes(m_face, 0, 48); setup_font_character(); } Font::~Font() { - + FT_Done_Face(m_face); FT_Done_FreeType(m_ft); glDeleteTextures(1, &m_text_texture); @@ -31,54 +31,35 @@ Font::~Font() { void Font::load_character(char8_t c) { if (FT_Load_Char(m_face, c, FT_LOAD_RENDER)) { - Logger::error("FREETYTPE: Failed to load Glyph"); - return; - } - const auto& width = m_face->glyph->bitmap.width; - const auto& height = m_face->glyph->bitmap.rows; - glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture); - glTexSubImage3D( - GL_TEXTURE_2D_ARRAY, - 0, - 0, - 0, - static_cast(c), - width, - height, - 1, - GL_RED, - GL_UNSIGNED_BYTE, - m_face->glyph->bitmap.buffer - ); + Logger::error("FREETYTPE: Failed to load Glyph"); + return; + } + const auto& width = m_face->glyph->bitmap.width; + const auto& height = m_face->glyph->bitmap.rows; + glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture); + glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, static_cast(c), width, + height, 1, GL_RED, GL_UNSIGNED_BYTE, + m_face->glyph->bitmap.buffer); - Character character = { - glm::vec2{0.0f, 0.0f}, - glm::vec2{static_cast(width) / m_texture_width, static_cast(height) / m_texture_height}, - glm::ivec2(m_face->glyph->bitmap.width, m_face->glyph->bitmap.rows), - glm::ivec2(m_face->glyph->bitmap_left, m_face->glyph->bitmap_top), - static_cast(m_face->glyph->advance.x) - }; + Character character = { + glm::vec2{0.0f, 0.0f}, + glm::vec2{static_cast(width) / m_texture_width, + static_cast(height) / m_texture_height}, + glm::ivec2(m_face->glyph->bitmap.width, m_face->glyph->bitmap.rows), + glm::ivec2(m_face->glyph->bitmap_left, m_face->glyph->bitmap_top), + static_cast(m_face->glyph->advance.x)}; - m_characters.insert({c, std::move(character)}); + m_characters.insert({c, std::move(character)}); } void Font::setup_font_character() { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - + glGenTextures(1, &m_text_texture); glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture); - glTexImage3D( - GL_TEXTURE_2D_ARRAY, - 0, - GL_RED, - m_texture_width, - m_texture_height, - MAX_CHARACTER, - 0, - GL_RED, - GL_UNSIGNED_BYTE, - nullptr - ); + glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RED, m_texture_width, + m_texture_height, MAX_CHARACTER, 0, GL_RED, GL_UNSIGNED_BYTE, + nullptr); for (char8_t c = 0; c < 128; c++) { load_character(c); @@ -88,12 +69,13 @@ void Font::setup_font_character() { glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glBindTexture(GL_TEXTURE_2D_ARRAY, 0); + glBindTexture(GL_TEXTURE_2D_ARRAY, 0); } -std::vector Font::vertices(const std::string &text, float x, float y, float scale) { +std::vector Font::vertices(const std::string& text, float x, float y, + float scale) { static Font font; - + std::vector vertices; for (char8_t c : text) { @@ -109,26 +91,27 @@ std::vector Font::vertices(const std::string &text, float x, float y, float w = ch.size.x * scale; float h = ch.size.y * scale; - vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, static_cast(c)); - vertices.emplace_back(xpos, ypos, ch.uv_min.x, ch.uv_min.y, static_cast(c)); - vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, static_cast(c)); - vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, static_cast(c)); - vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, static_cast(c)); - vertices.emplace_back(xpos + w, ypos + h, ch.uv_max.x, ch.uv_max.y, static_cast(c)); - + vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, + static_cast(c)); + vertices.emplace_back(xpos, ypos, ch.uv_min.x, ch.uv_min.y, + static_cast(c)); + vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, + static_cast(c)); + vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, + static_cast(c)); + vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, + static_cast(c)); + vertices.emplace_back(xpos + w, ypos + h, ch.uv_max.x, ch.uv_max.y, + static_cast(c)); + x += (ch.advance >> 6) * scale; - } return vertices; } -GLuint Font::text_texture() { - return m_text_texture; -} +GLuint Font::text_texture() { return m_text_texture; } -const std::string& Font::font_path() { - return m_font_path; -} +const std::string& Font::font_path() { return m_font_path; } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/tools/math_tools.cpp b/src/tools/math_tools.cpp index 6339ec8..0d9f29b 100644 --- a/src/tools/math_tools.cpp +++ b/src/tools/math_tools.cpp @@ -1,38 +1,42 @@ -#include +#include "Cubed/tools/math_tools.hpp" #include namespace Cubed { - namespace Math { - void extract_frustum_planes(const glm::mat4& mvp_matrix, std::vector& planes) { - if (planes.size() != 6) { - planes.resize(6); - } - - const float* m = glm::value_ptr(mvp_matrix); - - // left plane - planes[0] = glm::vec4(m[3] + m[0], m[7] + m[4], m[11] + m[8], m[15] + m[12]); - // right plane - planes[1] = glm::vec4(m[3] - m[0], m[7] - m[4], m[11] - m[8], m[15] - m[12]); - // bottom plane - planes[2] = glm::vec4(m[3] + m[1], m[7] + m[5], m[11] + m[9], m[15] + m[13]); - // top plane - planes[3] = glm::vec4(m[3] - m[1], m[7] - m[5], m[11] - m[9], m[15] - m[13]); - // near plane - planes[4] = glm::vec4(m[3] + m[2], m[7] + m[6], m[11] + m[10], m[15] + m[14]); - // far plane - planes[5] = glm::vec4(m[3] - m[2], m[7] - m[6], m[11] - m[10], m[15] - m[14]); - - for (auto& p : planes) { - p = glm::normalize(p); - } +void extract_frustum_planes(const glm::mat4& mvp_matrix, + std::vector& planes) { + if (planes.size() != 6) { + planes.resize(6); } - + const float* m = glm::value_ptr(mvp_matrix); + + // left plane + planes[0] = + glm::vec4(m[3] + m[0], m[7] + m[4], m[11] + m[8], m[15] + m[12]); + // right plane + planes[1] = + glm::vec4(m[3] - m[0], m[7] - m[4], m[11] - m[8], m[15] - m[12]); + // bottom plane + planes[2] = + glm::vec4(m[3] + m[1], m[7] + m[5], m[11] + m[9], m[15] + m[13]); + // top plane + planes[3] = + glm::vec4(m[3] - m[1], m[7] - m[5], m[11] - m[9], m[15] - m[13]); + // near plane + planes[4] = + glm::vec4(m[3] + m[2], m[7] + m[6], m[11] + m[10], m[15] + m[14]); + // far plane + planes[5] = + glm::vec4(m[3] - m[2], m[7] - m[6], m[11] - m[10], m[15] - m[14]); + + for (auto& p : planes) { + p = glm::normalize(p); + } } +} // namespace Math -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/tools/perlin_noise.cpp b/src/tools/perlin_noise.cpp index 95ee7e9..114e833 100644 --- a/src/tools/perlin_noise.cpp +++ b/src/tools/perlin_noise.cpp @@ -1,15 +1,15 @@ -#include +#include "Cubed/tools/perlin_noise.hpp" + +#include "Cubed/config.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/cubed_random.hpp" -#include -#include -#include #include #include #include namespace Cubed { - void PerlinNoise::init(unsigned seed) { p.resize(256); std::iota(p.begin(), p.end(), 0); @@ -41,27 +41,23 @@ float PerlinNoise::noise(float x, float y, float z) { int ba = p[b] + iz; int bb = p[b + 1] + iz; - float res = lerp (w, - lerp (v, - lerp(u, grad(p[aa], x, y, z), grad(p[ba], x - 1, y, z)), - lerp(u, grad(p[ab], x, y - 1, z), grad(p[bb], x - 1, y - 1, z)) - ), + float res = lerp( + w, + lerp(v, lerp(u, grad(p[aa], x, y, z), grad(p[ba], x - 1, y, z)), + lerp(u, grad(p[ab], x, y - 1, z), grad(p[bb], x - 1, y - 1, z))), lerp(v, - lerp(u, grad(p[aa + 1], x, y, z - 1), grad(p[ba + 1], x - 1, y, z - 1)), - lerp(u, grad(p[ab + 1], x, y - 1, z - 1), grad(p[bb + 1 ], x - 1, y - 1, z - 1)) - ) - + lerp(u, grad(p[aa + 1], x, y, z - 1), + grad(p[ba + 1], x - 1, y, z - 1)), + lerp(u, grad(p[ab + 1], x, y - 1, z - 1), + grad(p[bb + 1], x - 1, y - 1, z - 1))) + ); return (res + 1.0f) / 2.0f; } -float PerlinNoise::fade(float t) { - return t * t * t * (t * (t * 6 - 15) + 10); -} +float PerlinNoise::fade(float t) { return t * t * t * (t * (t * 6 - 15) + 10); } -float PerlinNoise::lerp(float t, float a, float b) { - return a + t * (b - a); -} +float PerlinNoise::lerp(float t, float a, float b) { return a + t * (b - a); } float PerlinNoise::grad(int hash, float x, float y, float z) { int h = hash & 15; @@ -83,4 +79,4 @@ void PerlinNoise::reload(unsigned seed) { is_init = true; } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/tools/shader_tools.cpp b/src/tools/shader_tools.cpp index 81127f9..f408114 100644 --- a/src/tools/shader_tools.cpp +++ b/src/tools/shader_tools.cpp @@ -1,140 +1,138 @@ -#include -#include +#include "Cubed/tools/shader_tools.hpp" -#include -#include -#include -#include +#include "Cubed/config.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/log.hpp" + +#include +#include namespace Cubed { - namespace fs = std::filesystem; namespace Tools { - GLuint create_shader_program(const std::string& v_shader_path, const std::string& f_shader_path) { +GLuint create_shader_program(const std::string& v_shader_path, + const std::string& f_shader_path) { - std::string v_shader_str = Tools::read_shader_source(ASSETS_PATH + v_shader_path); - std::string f_shader_str = Tools::read_shader_source(ASSETS_PATH + f_shader_path); - const char *v_shader_source = v_shader_str.c_str(); - const char *f_shader_source = f_shader_str.c_str(); + std::string v_shader_str = + Tools::read_shader_source(ASSETS_PATH + v_shader_path); + std::string f_shader_str = + Tools::read_shader_source(ASSETS_PATH + f_shader_path); + const char* v_shader_source = v_shader_str.c_str(); + const char* f_shader_source = f_shader_str.c_str(); - GLuint v_shader = glCreateShader(GL_VERTEX_SHADER); - GLuint f_shader = glCreateShader(GL_FRAGMENT_SHADER); + GLuint v_shader = glCreateShader(GL_VERTEX_SHADER); + GLuint f_shader = glCreateShader(GL_FRAGMENT_SHADER); - GLint vc, fc; - glShaderSource(v_shader, 1, &v_shader_source, NULL); - glShaderSource(f_shader, 1, &f_shader_source, NULL); - glCompileShader(v_shader); - Tools::check_opengl_error(); - glGetShaderiv(v_shader, GL_COMPILE_STATUS, &vc); - if (vc != 1) { - Logger::error("vertex compilation failed"); - Tools::print_shader_log(v_shader); - ASSERT(0); - } - glCompileShader(f_shader); - Tools::check_opengl_error(); - glGetShaderiv(f_shader, GL_COMPILE_STATUS, &fc); - if (fc != 1) { - Logger::error("vertex compilation failed"); - Tools::print_shader_log(f_shader); - ASSERT(0); - } - GLuint vf_program = glCreateProgram(); - glAttachShader(vf_program, v_shader); - glAttachShader(vf_program, f_shader); - glLinkProgram(vf_program); - - GLint linked; - Tools::check_opengl_error(); - glGetProgramiv(vf_program, GL_LINK_STATUS, &linked); - if (linked != 1) { - Logger::error("linking failed"); - Tools::print_program_info(vf_program); - ASSERT(0); - } - glDeleteShader(v_shader); - glDeleteShader(f_shader); - return vf_program; + GLint vc, fc; + glShaderSource(v_shader, 1, &v_shader_source, NULL); + glShaderSource(f_shader, 1, &f_shader_source, NULL); + glCompileShader(v_shader); + Tools::check_opengl_error(); + glGetShaderiv(v_shader, GL_COMPILE_STATUS, &vc); + if (vc != 1) { + Logger::error("vertex compilation failed"); + Tools::print_shader_log(v_shader); + ASSERT(0); } - - - void print_shader_log(GLuint shader) { - int len = 0; - int ch_written = 0; - char *log; - glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len); - if (len > 0) { - log = (char*)malloc(len); - glGetShaderInfoLog(shader, len, &ch_written, log); - Logger::info("Shader Info Log: {}", log); - free(log); - } - - } - - - void print_program_info(int prog) { - int len = 0; - int ch_written = 0; - char *log; - glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len); - if (len > 0) { - log = (char*)malloc(len); - glGetProgramInfoLog(prog, len, &ch_written, log); - Logger::info("Program Info Log: {}", log); - free(log); - } + glCompileShader(f_shader); + Tools::check_opengl_error(); + glGetShaderiv(f_shader, GL_COMPILE_STATUS, &fc); + if (fc != 1) { + Logger::error("vertex compilation failed"); + Tools::print_shader_log(f_shader); + ASSERT(0); } + GLuint vf_program = glCreateProgram(); + glAttachShader(vf_program, v_shader); + glAttachShader(vf_program, f_shader); + glLinkProgram(vf_program); - bool check_opengl_error() { - bool found_error = false; - int gl_err = glGetError(); - while (gl_err != GL_NO_ERROR) { - Logger::error("glEorr: {}", gl_err); - found_error = true; - gl_err = glGetError(); - } - - return found_error; + GLint linked; + Tools::check_opengl_error(); + glGetProgramiv(vf_program, GL_LINK_STATUS, &linked); + if (linked != 1) { + Logger::error("linking failed"); + Tools::print_program_info(vf_program); + ASSERT(0); } - - - std::string read_shader_source(const std::string& file_path) { - std::string content; - std::ifstream file_stream(file_path, std::ios::in); - - if (!file_stream.is_open()) { - Logger::error("{} not exist", file_path); - } - - std::string line = ""; - while (!file_stream.eof()) { - - getline(file_stream, line); - content.append(line + "\n"); - } - file_stream.close(); - return content; - } - - void delete_image_data(unsigned char* data) { - SOIL_free_image_data(data); - } - - unsigned char* load_image_data(const std::string& tex_image_path) { - fs::path path = ASSETS_PATH + tex_image_path; - ASSERT_MSG(fs::is_regular_file(path), path.c_str()); - unsigned char* data = nullptr; - int width, height, channels; - data = SOIL_load_image(path.string().c_str(), &width, &height, &channels, SOIL_LOAD_AUTO); - ASSERT_MSG(data, "Could not load texture" + path.string()); - - return data; - } - + glDeleteShader(v_shader); + glDeleteShader(f_shader); + return vf_program; } -} \ No newline at end of file +void print_shader_log(GLuint shader) { + int len = 0; + int ch_written = 0; + char* log; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len); + if (len > 0) { + log = (char*)malloc(len); + glGetShaderInfoLog(shader, len, &ch_written, log); + Logger::info("Shader Info Log: {}", log); + free(log); + } +} + +void print_program_info(int prog) { + int len = 0; + int ch_written = 0; + char* log; + glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len); + if (len > 0) { + log = (char*)malloc(len); + glGetProgramInfoLog(prog, len, &ch_written, log); + Logger::info("Program Info Log: {}", log); + free(log); + } +} + +bool check_opengl_error() { + bool found_error = false; + int gl_err = glGetError(); + while (gl_err != GL_NO_ERROR) { + Logger::error("glEorr: {}", gl_err); + found_error = true; + gl_err = glGetError(); + } + + return found_error; +} + +std::string read_shader_source(const std::string& file_path) { + std::string content; + std::ifstream file_stream(file_path, std::ios::in); + + if (!file_stream.is_open()) { + Logger::error("{} not exist", file_path); + } + + std::string line = ""; + while (!file_stream.eof()) { + + getline(file_stream, line); + content.append(line + "\n"); + } + file_stream.close(); + return content; +} + +void delete_image_data(unsigned char* data) { SOIL_free_image_data(data); } + +unsigned char* load_image_data(const std::string& tex_image_path) { + fs::path path = ASSETS_PATH + tex_image_path; + ASSERT_MSG(fs::is_regular_file(path), path.c_str()); + unsigned char* data = nullptr; + int width, height, channels; + data = SOIL_load_image(path.string().c_str(), &width, &height, &channels, + SOIL_LOAD_AUTO); + ASSERT_MSG(data, "Could not load texture" + path.string()); + + return data; +} + +} // namespace Tools + +} // namespace Cubed \ No newline at end of file diff --git a/src/ui/text.cpp b/src/ui/text.cpp index b9e8abc..a81dc93 100644 --- a/src/ui/text.cpp +++ b/src/ui/text.cpp @@ -1,26 +1,19 @@ -#include +#include "Cubed/ui/text.hpp" -#include -#include -#include +#include "Cubed/shader.hpp" +#include "Cubed/tools/cubed_hash.hpp" +#include "Cubed/tools/font.hpp" #include #include namespace Cubed { +Text::Text(std::string_view name) : NAME(name), UUID(HASH::str(name)) {} -Text::Text(std::string_view name) : - NAME(name), - UUID(HASH::str(name)) -{ - -} - -Text::Text(std::string_view name, std::string_view str, glm::vec2 pos, Color color) : - NAME(name), - UUID(HASH::str(name)) -{ +Text::Text(std::string_view name, std::string_view str, glm::vec2 pos, + Color color) + : NAME(name), UUID(HASH::str(name)) { m_text.assign(str); m_pos = pos; m_color = color_value(color); @@ -33,17 +26,11 @@ Text::~Text() { } } -Text::Text(Text&& other) noexcept : - m_scale(other.m_scale), - m_pos(other.m_pos), - NAME(other.NAME), - UUID(other.UUID), - m_text(std::move(other.m_text)), - m_color(other.m_color), - m_model_matrix(other.m_model_matrix), - m_vertices(std::move(other.m_vertices)), - m_vbo(other.m_vbo) -{ +Text::Text(Text&& other) noexcept + : m_scale(other.m_scale), m_pos(other.m_pos), NAME(other.NAME), + UUID(other.UUID), m_text(std::move(other.m_text)), m_color(other.m_color), + m_model_matrix(other.m_model_matrix), + m_vertices(std::move(other.m_vertices)), m_vbo(other.m_vbo) { other.m_vbo = 0; } @@ -62,9 +49,7 @@ Text& Text::scale(float s) { return *this; } -std::size_t Text::uuid() const { - return UUID; -} +std::size_t Text::uuid() const { return UUID; } void Text::set_loc(const Shader& shader) { m_color_loc = shader.loc("textColor"); @@ -78,22 +63,25 @@ Text& Text::text(std::string_view str) { } void Text::render() { - ASSERT_MSG(m_vbo != 0,"VBO not initialized!"); + ASSERT_MSG(m_vbo != 0, "VBO not initialized!"); ASSERT_MSG(!m_vertices.empty(), "Text String Not Set"); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_ARRAY, Font::text_texture()); ASSERT_MSG(m_color_loc, "m_color_loc is null"); - - m_model_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(m_pos.x, m_pos.y, 0.0f)) * - glm::scale(glm::mat4(1.0f), glm::vec3(m_scale, m_scale, 1.0f)); - + + m_model_matrix = + glm::translate(glm::mat4(1.0f), glm::vec3(m_pos.x, m_pos.y, 0.0f)) * + glm::scale(glm::mat4(1.0f), glm::vec3(m_scale, m_scale, 1.0f)); + glUniform3f(m_color_loc, m_color.x, m_color.y, m_color.z); glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_model_matrix)); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); - + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)0); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, s)); - glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, layer)); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), + (void*)offsetof(Vertex2D, s)); + glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), + (void*)offsetof(Vertex2D, layer)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); @@ -115,11 +103,10 @@ void Text::upload_to_gpu() { } ASSERT_MSG(m_vbo, "Vbo Is Not Gen"); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); - glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex2D), m_vertices.data(), GL_DYNAMIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex2D), + m_vertices.data(), GL_DYNAMIC_DRAW); } -bool Text::operator==(const Text& other) const { - return UUID == other.uuid(); -} +bool Text::operator==(const Text& other) const { return UUID == other.uuid(); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/src/window.cpp b/src/window.cpp index 3dbc886..09dafea 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -1,10 +1,10 @@ -#include -#include -#include -#include -#include +#include "Cubed/window.hpp" -#include +#include "Cubed/config.hpp" +#include "Cubed/renderer.hpp" +#include "Cubed/tools/cubed_assert.hpp" +#include "Cubed/tools/font.hpp" +#include "Cubed/tools/log.hpp" #include #include @@ -15,11 +15,7 @@ namespace Cubed { static int windowed_xpos = 0, windowed_ypos = 0; static int windowed_width = 800, windowed_height = 600; -Window::Window(Renderer& renderer) : - m_renderer(renderer) -{ - -} +Window::Window(Renderer& renderer) : m_renderer(renderer) {} Window::~Window() { @@ -31,62 +27,55 @@ Window::~Window() { glfwDestroyWindow(m_window); m_window = nullptr; } - + glfwTerminate(); } -bool Window::is_mouse_enable() const { - return m_mouse_enable; -} +bool Window::is_mouse_enable() const { return m_mouse_enable; } -const GLFWwindow* Window::get_glfw_window() const { - return m_window; -} +const GLFWwindow* Window::get_glfw_window() const { return m_window; } -GLFWwindow* Window::get_glfw_window() { - return m_window; -} +GLFWwindow* Window::get_glfw_window() { return m_window; } void Window::update_viewport() { glfwGetFramebufferSize(m_window, &m_width, &m_height); m_aspect = (float)m_width / (float)m_height; glViewport(0, 0, m_width, m_height); - m_renderer.update_proj_matrix(m_aspect, m_width, m_height) ; + m_renderer.update_proj_matrix(m_aspect, m_width, m_height); auto& config = Config::get(); config.set("window.width", windowed_width); config.set("window.height", windowed_height); - } void Window::init() { if (!glfwInit()) { Logger::error("glfw init fail"); - exit(EXIT_FAILURE); + exit(EXIT_FAILURE); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); - auto& config= Config::get(); + auto& config = Config::get(); m_width = config.get("window.width"); m_height = config.get("window.height"); if (config.get("window.fullscreen")) { GLFWmonitor* primary_monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(primary_monitor); - m_window = glfwCreateWindow(mode->width, mode->height, "Cubed", primary_monitor, NULL); + m_window = glfwCreateWindow(mode->width, mode->height, "Cubed", + primary_monitor, NULL); } else { m_window = glfwCreateWindow(m_width, m_height, "Cubed", NULL, NULL); } - + glfwMakeContextCurrent(m_window); if (config.get("window.V-Sync")) { - glfwSwapInterval(1); + glfwSwapInterval(1); } else { - glfwSwapInterval(0); + glfwSwapInterval(0); } - - + glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); if (glfwRawMouseMotionSupported()) { glfwSetInputMode(m_window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE); @@ -96,17 +85,17 @@ void Window::init() { GLFWmonitor* primary = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(primary); - glfwSetWindowPos(m_window, static_cast(mode->width / 2.0f) - 400, static_cast(mode->height / 2.0f) - 300); - + glfwSetWindowPos(m_window, static_cast(mode->width / 2.0f) - 400, + static_cast(mode->height / 2.0f) - 300); } void Window::hot_reload() { - auto& config= Config::get(); + auto& config = Config::get(); // V-Sync if (config.get("window.V-Sync")) { - glfwSwapInterval(1); + glfwSwapInterval(1); } else { - glfwSwapInterval(0); + glfwSwapInterval(0); } // Window windowed_width = config.get("window.width"); @@ -119,27 +108,14 @@ void Window::hot_reload() { GLFWmonitor* primary = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(primary); - glfwSetWindowMonitor( - m_window, - primary, - 0, - 0, - mode->width, - mode->height, - GL_DONT_CARE - ); + glfwSetWindowMonitor(m_window, primary, 0, 0, mode->width, mode->height, + GL_DONT_CARE); } else { GLFWmonitor* monitor = glfwGetWindowMonitor(m_window); if (monitor != nullptr) { - glfwSetWindowMonitor( - m_window, - nullptr, - windowed_xpos, - windowed_ypos, - windowed_width, - windowed_height, - 0 - ); + glfwSetWindowMonitor(m_window, nullptr, windowed_xpos, + windowed_ypos, windowed_width, windowed_height, + 0); } else { Logger::error("Can't Find Monitor"); } @@ -157,16 +133,9 @@ void Window::toggle_fullscreen() { auto& config = Config::get(); GLFWmonitor* monitor = glfwGetWindowMonitor(m_window); if (monitor != nullptr) { - glfwSetWindowMonitor( - m_window, - nullptr, - windowed_xpos, - windowed_ypos, - windowed_width, - windowed_height, - 0 - ); - + glfwSetWindowMonitor(m_window, nullptr, windowed_xpos, windowed_ypos, + windowed_width, windowed_height, 0); + config.set("window.fullscreen", false); } else { glfwGetWindowPos(m_window, &windowed_xpos, &windowed_ypos); @@ -175,33 +144,25 @@ void Window::toggle_fullscreen() { GLFWmonitor* primary = glfwGetPrimaryMonitor(); const GLFWvidmode* mode = glfwGetVideoMode(primary); - glfwSetWindowMonitor( - m_window, - primary, - 0, - 0, - mode->width, - mode->height, - GL_DONT_CARE - ); + glfwSetWindowMonitor(m_window, primary, 0, 0, mode->width, mode->height, + GL_DONT_CARE); config.set("window.fullscreen", true); - } update_viewport(); } void Window::toggle_mouse_able() { - //auto& io = ImGui::GetIO(); + // auto& io = ImGui::GetIO(); if (m_mouse_enable) { - //io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange; - //Logger::info("ImGuiConfigFlags_NoMouseCursorChange"); - //ImGui::SetMouseCursor(ImGuiMouseCursor_None); - //glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + // io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange; + // Logger::info("ImGuiConfigFlags_NoMouseCursorChange"); + // ImGui::SetMouseCursor(ImGuiMouseCursor_None); + // glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); m_mouse_enable = false; } else { - //io.ConfigFlags &= ~ImGuiConfigFlags_NoMouseCursorChange; - //Logger::info("Disable ImGuiConfigFlags_NoMouseCursorChange"); + // io.ConfigFlags &= ~ImGuiConfigFlags_NoMouseCursorChange; + // Logger::info("Disable ImGuiConfigFlags_NoMouseCursorChange"); glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); m_mouse_enable = true; } @@ -210,16 +171,25 @@ void Window::toggle_mouse_able() { void Window::imgui_init() { float dpi_scale_x, dpi_scale_y; glfwGetWindowContentScale(m_window, &dpi_scale_x, &dpi_scale_y); - //float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); + // float main_scale = + // ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); float main_scale = dpi_scale_x; Logger::info("Main Scale {}", main_scale); // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange; // Prevent ImGui from automatically changing the system cursor shape, allowing the game to fully control cursor appearance (e.g., hidden/disabled custom cursor). + io.ConfigFlags |= + ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= + ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= + ImGuiConfigFlags_NoMouseCursorChange; // Prevent ImGui from + // automatically changing the + // system cursor shape, allowing + // the game to fully control + // cursor appearance (e.g., + // hidden/disabled custom cursor). auto theme = Config::get().get("devpanel.theme"); if (theme == 0) { ImGui::StyleColorsDark(); @@ -229,16 +199,19 @@ void Window::imgui_init() { ImGui::StyleColorsDark(); Config::get().set("devpanel.theme", 0); } - + ImGuiStyle& style = ImGui::GetStyle(); - style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) + style.ScaleAllSizes( + main_scale); // Bake a fixed style scale. (until we have a solution for + // dynamic style scaling, changing this requires resetting + // Style + calling this again) style.FontScaleDpi = main_scale; style.FontSizeBase = 20.0f; ImFont* font = io.Fonts->AddFontFromFileTTF(Font::font_path().c_str()); ASSERT_MSG(font != nullptr, "Font Load Fail"); // Setup Platform/Renderer backends - ImGui_ImplGlfw_InitForOpenGL(m_window, false); + ImGui_ImplGlfw_InitForOpenGL(m_window, false); ImGui_ImplOpenGL3_Init(); } -} \ No newline at end of file +} // namespace Cubed \ No newline at end of file diff --git a/third_party/.clang-format b/third_party/.clang-format new file mode 100644 index 0000000..9d15924 --- /dev/null +++ b/third_party/.clang-format @@ -0,0 +1,2 @@ +DisableFormat: true +SortIncludes: false