chore: add clang-format and pre-commit configuration

This commit is contained in:
2026-04-28 09:22:55 +08:00
parent dc3be5a4bc
commit 611a795481
62 changed files with 2166 additions and 2134 deletions

321
.clang-format Normal file
View File

@@ -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
...

3
.clang-format-ignore Normal file
View File

@@ -0,0 +1,3 @@
third_party/
build/
vendor/

8
.pre-commit-config.yaml Normal file
View File

@@ -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/.*$'

View File

@@ -3,17 +3,12 @@
namespace Cubed { namespace Cubed {
struct AABB { struct AABB {
glm::vec3 min{0.0f, 0.0f, 0.0f}; glm::vec3 min{0.0f, 0.0f, 0.0f};
glm::vec3 max{0.0f, 0.0f, 0.0f}; glm::vec3 max{0.0f, 0.0f, 0.0f};
AABB(glm::vec3 min_point, glm::vec3 max_point): AABB(glm::vec3 min_point, glm::vec3 max_point)
min(min_point), : min(min_point), max(max_point) {}
max(max_point)
{
}
bool intersects(const AABB& other) const { bool intersects(const AABB& other) const {
return (min.x <= other.max.x && max.x >= other.min.x) && return (min.x <= other.max.x && max.x >= other.min.x) &&
@@ -22,4 +17,4 @@ struct AABB {
} }
}; };
} } // namespace Cubed

View File

@@ -1,24 +1,28 @@
#pragma once #pragma once
#define GLFW_INCLUDE_NONE
#include <Cubed/camera.hpp> #include "Cubed/camera.hpp"
#include <Cubed/dev_panel.hpp> #include "Cubed/dev_panel.hpp"
#include <Cubed/gameplay/world.hpp> #include "Cubed/gameplay/world.hpp"
#include <Cubed/input.hpp> #include "Cubed/renderer.hpp"
#include <Cubed/renderer.hpp> #include "Cubed/texture_manager.hpp"
#include <Cubed/texture_manager.hpp> #include "Cubed/window.hpp"
#include <Cubed/window.hpp>
namespace Cubed { namespace Cubed {
class App { class App {
public: public:
App(); App();
~App(); ~App();
static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos); static void cursor_position_callback(GLFWwindow* window, double xpos,
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); double ypos);
static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); 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_focus_callback(GLFWwindow* window, int focused);
static void window_reshape_callback(GLFWwindow* window, int new_width, int new_height); static void window_reshape_callback(GLFWwindow* window, int new_width,
static void mouse_scroll_callback(GLFWwindow* window, double xoffset, double yoffset); 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 cursor_enter_callback(GLFWwindow* window, int entered);
static void char_callback(GLFWwindow* window, unsigned int ch); static void char_callback(GLFWwindow* window, unsigned int ch);
static int start_cubed_application(int argc, char** argv); static int start_cubed_application(int argc, char** argv);
@@ -34,7 +38,6 @@ public:
Window& window(); Window& window();
World& world(); World& world();
private: private:
Camera m_camera; Camera m_camera;
TextureManager m_texture_manager; TextureManager m_texture_manager;
@@ -62,4 +65,4 @@ private:
void update(); void update();
}; };
} } // namespace Cubed

View File

@@ -1,27 +1,23 @@
#pragma once #pragma once
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp> #include <glm/gtc/type_ptr.hpp>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
namespace Cubed { namespace Cubed {
class Player; class Player;
class Camera { class Camera {
private: private:
bool m_firse_mouse = true; bool m_firse_mouse = true;
Player* m_player; Player* m_player;
float m_last_mouse_x, m_last_mouse_y; float m_last_mouse_x, m_last_mouse_y;
glm::vec3 m_camera_pos; glm::vec3 m_camera_pos;
public: public:
Camera(); Camera();
void update_move_camera(); void update_move_camera();
@@ -35,6 +31,4 @@ public:
const glm::vec3& get_camera_pos() const; const glm::vec3& get_camera_pos() const;
}; };
} } // namespace Cubed

View File

@@ -1,22 +1,16 @@
#pragma once #pragma once
#include <toml++/toml.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <Cubed/tools/cubed_assert.hpp> #include <toml++/toml.hpp>
namespace Cubed { namespace Cubed {
template <typename T> template <typename T>
concept TomlValueType = concept TomlValueType =
std::same_as<T, int> || std::same_as<T, int> || std::same_as<T, bool> || std::same_as<T, double> ||
std::same_as<T, bool> || std::same_as<T, const char*> || std::same_as<T, toml::date> ||
std::same_as<T, double> || std::same_as<T, toml::time> || std::same_as<T, toml::date_time> ||
std::same_as<T, const char*> || std::same_as<T, std::string>;
std::same_as<T, toml::date> ||
std::same_as<T, toml::time> ||
std::same_as<T, toml::date_time> ||
std::same_as<T, std::string>
;
class Config { class Config {
public: public:
@@ -30,8 +24,7 @@ public:
void load_or_create_config(); void load_or_create_config();
void save_to_file(); void save_to_file();
template <TomlValueType T> template <TomlValueType T> T get(std::string_view key) const {
T get(std::string_view key) const{
size_t cur = 0; size_t cur = 0;
auto pos = key.find('.'); auto pos = key.find('.');
const toml::table* table = &m_tbl; const toml::table* table = &m_tbl;
@@ -67,8 +60,7 @@ public:
std::abort(); std::abort();
} }
} }
template <typename T> template <typename T> void set(std::string_view key, T&& val) {
void set(std::string_view key, T&& val) {
if constexpr (!TomlValueType<std::decay_t<T>>) { if constexpr (!TomlValueType<std::decay_t<T>>) {
static_assert(false, "Type Not Support"); static_assert(false, "Type Not Support");
} }
@@ -90,7 +82,6 @@ public:
auto [it, inserted] = table->insert_or_assign(s, toml::table{}); auto [it, inserted] = table->insert_or_assign(s, toml::table{});
table = it->second.as_table(); table = it->second.as_table();
} }
} }
std::string_view n_key = key.substr(cur); std::string_view n_key = key.substr(cur);
if (n_key.empty()) { if (n_key.empty()) {
@@ -99,21 +90,18 @@ public:
std::abort(); std::abort();
} }
table->insert_or_assign(n_key, std::forward<T>(val)); table->insert_or_assign(n_key, std::forward<T>(val));
} }
template <typename T> template <typename T> void set_and_save(std::string_view key, T&& val) {
void set_and_save(std::string_view key, T&& val) {
set(key, std::forward(val)); set(key, std::forward(val));
save_to_file(); save_to_file();
} }
toml::node_view<toml::node> val_view(std::string_view key); toml::node_view<toml::node> val_view(std::string_view key);
private: private:
toml::table m_tbl; 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(); void create_config();
}; };
} } // namespace Cubed

View File

@@ -24,4 +24,4 @@ constexpr float DEFAULT_G = 22.5f;
using HeightMapArray = std::array<std::array<float, CHUCK_SIZE>, CHUCK_SIZE>; using HeightMapArray = std::array<std::array<float, CHUCK_SIZE>, CHUCK_SIZE>;
} } // namespace Cubed

View File

@@ -1,13 +1,11 @@
#pragma once #pragma once
#include <Cubed/primitive_data.hpp> #include "Cubed/ui/text.hpp"
#include <Cubed/ui/text.hpp>
#include <unordered_map> #include <unordered_map>
namespace Cubed { namespace Cubed {
class DebugCollector { class DebugCollector {
public: public:
static DebugCollector& get(); static DebugCollector& get();
@@ -23,4 +21,4 @@ private:
std::unordered_map<std::size_t, Text> m_texts; std::unordered_map<std::size_t, Text> m_texts;
}; };
} } // namespace Cubed

View File

@@ -29,6 +29,7 @@ class DevPanel {
struct TextEditing { struct TextEditing {
bool perlin_seed = false; bool perlin_seed = false;
}; };
public: public:
DevPanel(App& app); DevPanel(App& app);
void init(); void init();
@@ -50,8 +51,6 @@ private:
void update_config_view(); void update_config_view();
void update_player_profile(); void update_player_profile();
}; };
} // namespace Cubed
}

View File

@@ -12,14 +12,7 @@ constexpr float FOREST_FREQ = 1.2f;
constexpr float DESERT_FREQ = 1.2f; constexpr float DESERT_FREQ = 1.2f;
constexpr float MOUNTAIN_FREQ = 2.0f; constexpr float MOUNTAIN_FREQ = 2.0f;
enum class Biome { enum class Biome { PLAIN = 0, FOREST, DESERT, MOUNTAIN, NONE };
PLAIN = 0,
FOREST,
DESERT,
MOUNTAIN,
NONE
};
struct BiomeHeightRange { struct BiomeHeightRange {
int base_y; int base_y;
@@ -32,12 +25,11 @@ struct BiomeNonAdjacent {
Biome replace; Biome replace;
}; };
static inline const std::vector<BiomeNonAdjacent> NON_ADJACENT {{ static inline const std::vector<BiomeNonAdjacent> NON_ADJACENT{
{Biome::PLAIN, {Biome::NONE}, Biome::PLAIN}, {{Biome::PLAIN, {Biome::NONE}, Biome::PLAIN},
{Biome::FOREST, {Biome::DESERT}, Biome::PLAIN}, {Biome::FOREST, {Biome::DESERT}, Biome::PLAIN},
{Biome::DESERT, {Biome::MOUNTAIN, Biome::FOREST}, Biome::PLAIN}, {Biome::DESERT, {Biome::MOUNTAIN, Biome::FOREST}, Biome::PLAIN},
{Biome::MOUNTAIN, {Biome::DESERT}, Biome::PLAIN} {Biome::MOUNTAIN, {Biome::DESERT}, Biome::PLAIN}}};
}};
struct BaseBiomeParams { struct BaseBiomeParams {
Biome biome; Biome biome;
@@ -47,32 +39,27 @@ struct BaseBiomeParams {
BiomeHeightRange height_range; BiomeHeightRange height_range;
}; };
struct PlainParams : public BaseBiomeParams { struct PlainParams : public BaseBiomeParams {};
};
struct ForestParams : public BaseBiomeParams { struct ForestParams : public BaseBiomeParams {
float tree_frequency; 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); std::string get_biome_str(Biome biome);
Biome get_biome_from_noise(float temp, float humid); Biome get_biome_from_noise(float temp, float humid);
std::array<float, 3> get_noise_frequencies_for_biome(Biome biome); std::array<float, 3> get_noise_frequencies_for_biome(Biome biome);
BiomeHeightRange get_biome_height_range(Biome biome); BiomeHeightRange get_biome_height_range(Biome biome);
Biome safe_int_to_biome(int x); 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(); PlainParams& plain_params();
ForestParams& forest_params(); ForestParams& forest_params();
DesertParams& desert_params(); DesertParams& desert_params();
MountainParams& mountain_params(); MountainParams& mountain_params();
} } // namespace Cubed

View File

@@ -1,26 +1,22 @@
#pragma once #pragma once
#include "Cubed/constants.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include <array>
#include <glad/glad.h> #include <glad/glad.h>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <array>
#include <string> #include <string>
#include <vector> #include <vector>
#include <Cubed/config.hpp>
#include <Cubed/constants.hpp>
#include <Cubed/tools/cubed_assert.hpp>
namespace Cubed { namespace Cubed {
struct BlockTexture { struct BlockTexture {
std::string name; std::string name;
unsigned id; unsigned id;
std::vector<GLuint> texture; std::vector<GLuint> texture;
}; };
struct Block : public BlockTexture{ struct Block : public BlockTexture {};
};
struct BlockRenderData { struct BlockRenderData {
std::vector<bool> draw_face; std::vector<bool> draw_face;
@@ -28,12 +24,8 @@ struct BlockRenderData {
BlockRenderData() = default; BlockRenderData() = default;
BlockRenderData(const BlockRenderData&) = default; BlockRenderData(const BlockRenderData&) = default;
BlockRenderData& operator=(const BlockRenderData&) = default; BlockRenderData& operator=(const BlockRenderData&) = default;
BlockRenderData(BlockRenderData&& data) : BlockRenderData(BlockRenderData&& data)
draw_face(std::move(data.draw_face)), : draw_face(std::move(data.draw_face)), block_id(data.block_id) {}
block_id(data.block_id)
{
}
BlockRenderData& operator=(BlockRenderData&& data) { BlockRenderData& operator=(BlockRenderData&& data) {
draw_face = std::move(data.draw_face); draw_face = std::move(data.draw_face);
block_id = data.block_id; block_id = data.block_id;
@@ -47,29 +39,14 @@ struct LookBlock {
}; };
constexpr std::array<std::string_view, MAX_BLOCK_NUM> BLOCK_REISTER{ constexpr std::array<std::string_view, MAX_BLOCK_NUM> BLOCK_REISTER{
"air", "air", "grass_block", "dirt", "stone", "sand", "log", "leaf"};
"grass_block",
"dirt",
"stone",
"sand",
"log",
"leaf"
};
const std::array<bool, MAX_BLOCK_NUM> TRANSPARENT_MAP{ const std::array<bool, MAX_BLOCK_NUM> TRANSPARENT_MAP{
true, true, false, false, false, false, false, true};
false,
false,
false,
false,
false,
true
};
inline bool is_in_transparent_map(unsigned id) { inline bool is_in_transparent_map(unsigned id) {
ASSERT_MSG(id < MAX_BLOCK_NUM, "ID is invaild"); ASSERT_MSG(id < MAX_BLOCK_NUM, "ID is invaild");
return TRANSPARENT_MAP[id]; return TRANSPARENT_MAP[id];
}; };
} // namespace Cubed
}

View File

@@ -1,18 +1,16 @@
#pragma once #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 <atomic> #include <atomic>
#include <cstdint> #include <cstdint>
#include <Cubed/config.hpp>
#include <Cubed/primitive_data.hpp>
#include <Cubed/gameplay/biome.hpp>
#include <Cubed/gameplay/chunk_generator.hpp>
#include <Cubed/gameplay/chunk_pos.hpp>
#include <Cubed/gameplay/block.hpp>
namespace Cubed { namespace Cubed {
class World; 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 { class Chunk {
@@ -66,11 +64,13 @@ public:
// Generate heightmap using biome-specific noise // Generate heightmap using biome-specific noise
void gen_phase_three(); void gen_phase_three();
// Blend heightmap with neighbors for smooth transitions // Blend heightmap with neighbors for smooth transitions
void gen_phase_four(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap); void gen_phase_four(
const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap);
// Generate terrain blocks from heightmap and biome // Generate terrain blocks from heightmap and biome
void gen_phase_five(); void gen_phase_five();
// Blend surface blocks at chunk borders with neighbors // Blend surface blocks at chunk borders with neighbors
void gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block); void gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>, 4>&
neighbor_block);
// Generate biome-specific vegetation/structures // Generate biome-specific vegetation/structures
void gen_phase_seven(); void gen_phase_seven();
// void gen_vertex_data(); // void gen_vertex_data();
@@ -78,7 +78,8 @@ public:
// 1 : (-1, 0) // 1 : (-1, 0)
// 2 : (0, 1) // 2 : (0, 1)
// 3 : (0, -1) // 3 : (0, -1)
void gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& neighbor_block); void gen_vertex_data(
const std::array<const std::vector<uint8_t>*, 4>& neighbor_block);
void upload_to_gpu(); void upload_to_gpu();
GLuint get_vbo() const; GLuint get_vbo() const;
@@ -99,5 +100,4 @@ public:
std::vector<uint8_t>& blocks(); std::vector<uint8_t>& blocks();
}; };
} // namespace Cubed
}

View File

@@ -1,20 +1,21 @@
#pragma once #pragma once
#include <Cubed/constants.hpp> #include "Cubed/constants.hpp"
#include <Cubed/tools/cubed_random.hpp> #include "Cubed/tools/cubed_random.hpp"
#include <atomic> #include <atomic>
#include <optional> #include <optional>
namespace Cubed { namespace Cubed {
class Chunk; class Chunk;
class ChunkGenerator { class ChunkGenerator {
static constexpr int SIZE_X = CHUCK_SIZE; static constexpr int SIZE_X = CHUCK_SIZE;
static constexpr int SIZE_Y = WORLD_SIZE_Y; static constexpr int SIZE_Y = WORLD_SIZE_Y;
static constexpr int SIZE_Z = CHUCK_SIZE; static constexpr int SIZE_Z = CHUCK_SIZE;
using HeightMapArray = std::array<std::array<float, CHUCK_SIZE>, CHUCK_SIZE>; using HeightMapArray =
std::array<std::array<float, CHUCK_SIZE>, CHUCK_SIZE>;
public: public:
ChunkGenerator(Chunk& chunk); ChunkGenerator(Chunk& chunk);
@@ -26,15 +27,19 @@ public:
// Generate Biome // Generate Biome
void assign_chunk_biome(); void assign_chunk_biome();
// Adjust Biome // Adjust Biome
void resolve_biome_adjacency_conflict(const std::array<const Chunk*, 4>& adj_chunks); void resolve_biome_adjacency_conflict(
const std::array<const Chunk*, 4>& adj_chunks);
// Generate Heightmap // Generate Heightmap
void generate_heightmap(); void generate_heightmap();
// Adjust Height // Adjust Height
void blend_heightmap_boundaries(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap); void blend_heightmap_boundaries(
const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap);
// Generate Block // Generate Block
void generate_terrain_blocks(); void generate_terrain_blocks();
// Adjust Block; // Adjust Block;
void blend_surface_blocks_borders(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block); void blend_surface_blocks_borders(
const std::array<std::optional<std::vector<uint8_t>>, 4>&
neighbor_block);
// Generate Structure // Generate Structure
void generate_vegetation(); void generate_vegetation();
@@ -46,5 +51,4 @@ private:
Random m_random; Random m_random;
}; };
} // namespace Cubed
}

View File

@@ -1,13 +1,9 @@
#pragma once #pragma once
#include <functional> #include <functional>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/cubed_assert.hpp>
namespace Cubed { namespace Cubed {
struct ChunkPos { struct ChunkPos {
int x; int x;
int z; int z;
@@ -32,5 +28,4 @@ struct ChunkPos {
}; };
}; };
} // namespace Cubed
}

View File

@@ -5,11 +5,7 @@
namespace Cubed { namespace Cubed {
enum class GameMode { CREATIVE = 0, SPECTATOR };
enum class GameMode {
CREATIVE = 0,
SPECTATOR
};
inline std::string to_str(GameMode mode) { inline std::string to_str(GameMode mode) {
using enum GameMode; using enum GameMode;
@@ -22,5 +18,4 @@ inline std::string to_str(GameMode mode) {
throw std::invalid_argument{"GameMode is invaild"}; throw std::invalid_argument{"GameMode is invaild"};
} }
} // namespace Cubed
}

View File

@@ -1,23 +1,18 @@
#pragma once #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 <glm/glm.hpp> #include <glm/glm.hpp>
#include <Cubed/AABB.hpp>
#include <Cubed/config.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 <optional> #include <optional>
#include <string> #include <string>
namespace Cubed { namespace Cubed {
enum class Gait{ enum class Gait { WALK = 0, RUN };
WALK = 0,
RUN
};
class World; class World;
@@ -65,7 +60,9 @@ private:
std::string m_name{}; std::string m_name{};
World& m_world; 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 check_player_chunk_transition();
void update_direction(); void update_direction();
@@ -102,8 +99,6 @@ public:
Gait& gait(); Gait& gait();
GameMode& game_mode(); GameMode& game_mode();
}; };
} // namespace Cubed
}

View File

@@ -13,4 +13,4 @@ struct TreeStructNode {
bool build_tree(Chunk& chunk, const glm::ivec3& pos); bool build_tree(Chunk& chunk, const glm::ivec3& pos);
} } // namespace Cubed

View File

@@ -1,14 +1,14 @@
#pragma once #pragma once
#include "Cubed/AABB.hpp"
#include "Cubed/gameplay/chunk.hpp"
#include <atomic> #include <atomic>
#include <condition_variable> #include <condition_variable>
#include <mutex> #include <mutex>
#include <thread>
#include <optional> #include <optional>
#include <thread>
#include <unordered_map> #include <unordered_map>
#include <unordered_set> #include <unordered_set>
#include <Cubed/AABB.hpp>
#include <Cubed/primitive_data.hpp>
#include <Cubed/gameplay/chunk.hpp>
namespace Cubed { namespace Cubed {
@@ -19,14 +19,14 @@ struct ChunkRenderSnapshot {
glm::vec3 half_extents; glm::vec3 half_extents;
}; };
class Player; class Player;
class World { class World {
private: private:
using ChunkPtrUpdateList = std::vector<std::pair<ChunkPos, Chunk*>>; using ChunkPtrUpdateList = std::vector<std::pair<ChunkPos, Chunk*>>;
using ChunkUpdateList = std::vector<std::pair<ChunkPos, Chunk>>; using ChunkUpdateList = std::vector<std::pair<ChunkPos, Chunk>>;
using ConstChunkMap = std::unordered_map<ChunkPos, const Chunk*, ChunkPos::Hash>; using ConstChunkMap =
std::unordered_map<ChunkPos, const Chunk*, ChunkPos::Hash>;
using ChunkPosSet = std::unordered_set<ChunkPos, ChunkPos::Hash>; using ChunkPosSet = std::unordered_set<ChunkPos, ChunkPos::Hash>;
glm::vec3 m_gen_player_pos{0.0f, 0.0f, 0.0f}; glm::vec3 m_gen_player_pos{0.0f, 0.0f, 0.0f};
@@ -58,26 +58,32 @@ private:
void gen_chunks_internal(); void gen_chunks_internal();
void sync_player_pos(glm::vec3& player_pos); void sync_player_pos(glm::vec3& player_pos);
void compute_required_chunks(ChunkPosSet& required_chunks); void compute_required_chunks(ChunkPosSet& required_chunks);
void sync_and_collect_missing_chunks(std::vector<ChunkPos>& , const ChunkPosSet&); void sync_and_collect_missing_chunks(std::vector<ChunkPos>&,
void build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neighbor, ChunkPtrUpdateList& affected_neighbor, const ChunkUpdateList& new_chunks); const ChunkPosSet&);
void build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList&, ConstChunkMap&); 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 start_gen_thread();
void stop_gen_thread(); void stop_gen_thread();
public: public:
World(); World();
~World(); ~World();
bool can_move(const AABB& player_box) const; bool can_move(const AABB& player_box) const;
// const BlockRenderData& get_block_render_data(int x, int y ,int z); // const BlockRenderData& get_block_render_data(int x, int y ,int z);
const std::optional<LookBlock>& get_look_block_pos(const std::string& name) const; const std::optional<LookBlock>&
get_look_block_pos(const std::string& name) const;
const Chunk* get_chunk(const ChunkPos& pos) const; const Chunk* get_chunk(const ChunkPos& pos) const;
Player& get_player(const std::string& name); Player& get_player(const std::string& name);
void init_world(); 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; int get_block(const glm::ivec3& block_pos) const;
bool is_block(const glm::ivec3& block_pos) const; bool is_block(const glm::ivec3& block_pos) const;
@@ -101,4 +107,4 @@ public:
void rendering_distance(int rendering_distance); void rendering_distance(int rendering_distance);
}; };
} } // namespace Cubed

View File

@@ -4,7 +4,6 @@
namespace Cubed { namespace Cubed {
struct MoveState { struct MoveState {
bool forward = false; bool forward = false;
bool back = false; bool back = false;
@@ -32,8 +31,6 @@ struct InputState {
namespace Input { namespace Input {
InputState& get_input_state(); InputState& get_input_state();
} }
} // namespace Cubed
}

View File

@@ -8,12 +8,12 @@ class MapTable {
private: private:
static std::unordered_map<unsigned, std::string> id_to_name_map; static std::unordered_map<unsigned, std::string> id_to_name_map;
static std::unordered_map<size_t, unsigned> name_to_id_map; static std::unordered_map<size_t, unsigned> name_to_id_map;
public: public:
// please using reference // please using reference
static const std::string& get_name_from_id(unsigned id); static const std::string& get_name_from_id(unsigned id);
static unsigned get_id_from_name(const std::string& name); static unsigned get_id_from_name(const std::string& name);
static void init_map(); static void init_map();
}; };
} } // namespace Cubed

View File

@@ -92,23 +92,12 @@ constexpr float TEX_COORDS[6][6][2] = {
{0.0f, 0.0f}} // front left {0.0f, 0.0f}} // front left
}; };
constexpr float CUBE_VER[24] = { 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, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0,
1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.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,
constexpr int OUTLINE_CUBE_INDICES[24] = { 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7};
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] = { constexpr float SQUARE_VERTICES[6][2] = {
{-0.5f, -0.5f}, // bottom left {-0.5f, -0.5f}, // bottom left
@@ -120,12 +109,8 @@ constexpr float SQUARE_VERTICES[6][2] = {
}; };
constexpr float SQUARE_TEXTURE_POS[6][2] = { constexpr float SQUARE_TEXTURE_POS[6][2] = {
{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f},
{0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f}, {0.0f, 0.0f},
{1.0f, 1.0f},
{1.0f, 1.0f},
{1.0f, 0.0f},
{0.0f, 0.0f},
}; };
struct Vertex { struct Vertex {
@@ -140,4 +125,4 @@ struct Vertex2D {
float layer = 0.0f; float layer = 0.0f;
}; };
} } // namespace Cubed

View File

@@ -1,12 +1,10 @@
#pragma once #pragma once
#include <Cubed/config.hpp> #include "Cubed/constants.hpp"
#include <Cubed/constants.hpp> #include "Cubed/primitive_data.hpp"
#include <Cubed/primitive_data.hpp> #include "Cubed/shader.hpp"
#include <Cubed/shader.hpp> #include "Cubed/ui/text.hpp"
#include <Cubed/ui/text.hpp>
#include <glad/glad.h>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <vector> #include <vector>
namespace Cubed { namespace Cubed {
@@ -19,7 +17,8 @@ class Renderer {
public: public:
constexpr static int NUM_VAO = 5; 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(); ~Renderer();
void hot_reload(); void hot_reload();
void init(); void init();
@@ -27,8 +26,8 @@ public:
void render(); void render();
void update_fov(float fov); void update_fov(float fov);
void update_proj_matrix(float aspect, float width, float height); void update_proj_matrix(float aspect, float width, float height);
private:
private:
const Camera& m_camera; const Camera& m_camera;
DevPanel& m_dev_panel; DevPanel& m_dev_panel;
const TextureManager& m_texture_manager; const TextureManager& m_texture_manager;
@@ -63,4 +62,4 @@ private:
void render_dev_panel(); void render_dev_panel();
}; };
} } // namespace Cubed

View File

@@ -1,22 +1,22 @@
#pragma once #pragma once
#include <glad/glad.h> #include <glad/glad.h>
#include <string> #include <string>
namespace Cubed { namespace Cubed {
class Shader { class Shader {
public: public:
Shader(); 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();
Shader(const Shader&) = delete; Shader(const Shader&) = delete;
Shader& operator=(const Shader&) = delete; Shader& operator=(const Shader&) = delete;
Shader(Shader&& shader) noexcept; Shader(Shader&& shader) noexcept;
Shader& operator=(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; std::size_t hash() const;
GLuint loc(const std::string& loc) const; GLuint loc(const std::string& loc) const;
const std::string& name() const; const std::string& name() const;
@@ -26,7 +26,6 @@ private:
GLuint m_program = 0; GLuint m_program = 0;
std::size_t m_hash = 0; std::size_t m_hash = 0;
std::string m_name = "-1"; std::string m_name = "-1";
}; };
} } // namespace Cubed

View File

@@ -1,11 +1,10 @@
#pragma once #pragma once
#include "Cubed/gameplay/block.hpp"
#include <glad/glad.h> #include <glad/glad.h>
#include <Cubed/gameplay/block.hpp>
#include <Cubed/tools/shader_tools.hpp>
namespace Cubed { namespace Cubed {
class TextureManager { class TextureManager {
private: private:
bool m_need_reload = false; bool m_need_reload = false;
@@ -34,5 +33,4 @@ public:
int max_aniso() const; int max_aniso() const;
}; };
} // namespace Cubed
}

View File

@@ -1,24 +1,20 @@
#pragma once #pragma once
#include <Cubed/tools/log.hpp> #include "Cubed/tools/log.hpp"
namespace Cubed { namespace Cubed {
namespace Assert { namespace Assert {
inline void msg(const char* condition, const char* file, inline void msg(const char* condition, const char* file, int line,
int line, const char* func, const char* func, std::string_view message = "") {
std::string_view message = ""
) {
Logger::error("Assertion failed: {} at {}: {} in function {}", Logger::error("Assertion failed: {} at {}: {} in function {}", condition,
condition, file, line, func); file, line, func);
if (message.size()) { if (message.size()) {
Logger::error("Message: {}", message); Logger::error("Message: {}", message);
} }
std::abort(); std::abort();
}
} }
} // namespace Assert
#ifdef DEBUG_MODE #ifdef DEBUG_MODE
#define ASSERT(cond) \ #define ASSERT(cond) \
@@ -30,7 +26,8 @@ namespace Assert {
#define ASSERT_MSG(cond, message) \ #define ASSERT_MSG(cond, message) \
do { \ do { \
if (!(cond)) { \ if (!(cond)) { \
::Cubed::Assert::msg(#cond, __FILE__, __LINE__, __func__, message); \ ::Cubed::Assert::msg(#cond, __FILE__, __LINE__, __func__, \
message); \
} \ } \
} while (0) } while (0)
@@ -39,4 +36,4 @@ namespace Assert {
#define ASSERT_MSG(cond, message) ((void)0) #define ASSERT_MSG(cond, message) ((void)0)
#endif #endif
} } // namespace Cubed

View File

@@ -1,9 +1,8 @@
#pragma once #pragma once
#include <string_view>
#include <cstdint> #include <cstdint>
#include <string_view>
namespace Cubed { namespace Cubed {
namespace HASH { namespace HASH {
inline std::size_t str(std::string_view value) { inline std::size_t str(std::string_view value) {
return std::hash<std::string_view>{}(value); return std::hash<std::string_view>{}(value);
@@ -28,6 +27,6 @@ namespace HASH {
return h; return h;
} }
} } // namespace HASH
} } // namespace Cubed

View File

@@ -17,5 +17,4 @@ private:
std::mt19937 m_engine; std::mt19937 m_engine;
}; };
} // namespace Cubed
}

View File

@@ -2,17 +2,15 @@
#include <ft2build.h> #include <ft2build.h>
#include FT_FREETYPE_H #include FT_FREETYPE_H
#include "Cubed/primitive_data.hpp"
#include <glad/glad.h> #include <glad/glad.h>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <Cubed/primitive_data.hpp>
namespace Cubed { namespace Cubed {
struct Character { struct Character {
glm::vec2 uv_min; glm::vec2 uv_min;
glm::vec2 uv_max; glm::vec2 uv_max;
@@ -28,9 +26,12 @@ public:
Font(); Font();
~Font(); ~Font();
static std::vector<Vertex2D> vertices(const std::string& text, float x = 0.0f, float y = 0.0f, float scale = 1.0f); static std::vector<Vertex2D> vertices(const std::string& text,
float x = 0.0f, float y = 0.0f,
float scale = 1.0f);
static GLuint text_texture(); static GLuint text_texture();
static const std::string& font_path(); static const std::string& font_path();
private: private:
FT_Library m_ft; FT_Library m_ft;
FT_Face m_face; FT_Face m_face;
@@ -39,13 +40,12 @@ private:
float m_texture_height = 64; float m_texture_height = 64;
static inline GLuint m_text_texture; 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<char8_t, Character> m_characters; std::unordered_map<char8_t, Character> m_characters;
void load_character(char8_t c); void load_character(char8_t c);
void setup_font_character(); void setup_font_character();
}; };
} } // namespace Cubed

View File

@@ -1,83 +1,70 @@
#pragma once #pragma once
#include <syncstream>
#include <iostream>
#include <chrono> #include <chrono>
#include <format> #include <format>
#include <iostream>
#include <source_location> #include <source_location>
#include <string> #include <string>
#include <syncstream>
namespace Cubed { namespace Cubed {
namespace Logger { namespace Logger {
enum class Level { enum class Level { TRACE, DEBUG, INFO, ERROR, WARN };
TRACE,
DEBUG,
INFO,
ERROR,
WARN
};
template <typename... Args> template <typename... Args>
inline void info(std::format_string<Args...> fmt, Args&&... args) { inline void info(std::format_string<Args...> fmt, Args&&... args) {
auto now_time = std::chrono:: auto now_time = std::chrono::time_point_cast<std::chrono::seconds>(
time_point_cast<std::chrono::seconds> std::chrono::system_clock::now());
(std::chrono::system_clock::now());
std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); std::string msg = std::vformat(fmt.get(), std::make_format_args(args...));
std::osyncstream(std::cout) << "\033[1;32m" std::osyncstream(std::cout)
<< std::format("[INFO][{:%Y-%m-%d %H:%M:%S}]", now_time) << "\033[1;32m" << std::format("[INFO][{:%Y-%m-%d %H:%M:%S}]", now_time)
<< msg << msg << "\033[0m"
<< "\033[0m"
<< "\n"; << "\n";
} }
template <typename... Args> template <typename... Args>
inline void error(std::format_string<Args...> fmt, Args&&... args) { inline void error(std::format_string<Args...> fmt, Args&&... args) {
auto now_time = std::chrono:: auto now_time = std::chrono::time_point_cast<std::chrono::seconds>(
time_point_cast<std::chrono::seconds> std::chrono::system_clock::now());
(std::chrono::system_clock::now());
std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); std::string msg = std::vformat(fmt.get(), std::make_format_args(args...));
std::osyncstream(std::cerr) << "\033[1;31m" std::osyncstream(std::cerr)
<< std::format("[ERROR][{:%Y-%m-%d %H:%M:%S}]", now_time) << "\033[1;31m"
<< msg << std::format("[ERROR][{:%Y-%m-%d %H:%M:%S}]", now_time) << msg
<< "\033[0m" << "\033[0m"
<< "\n"; << "\n";
} }
template <typename... Args> template <typename... Args>
inline void warn(std::format_string<Args...> fmt, Args&&... args) { inline void warn(std::format_string<Args...> fmt, Args&&... args) {
auto now_time = std::chrono:: auto now_time = std::chrono::time_point_cast<std::chrono::seconds>(
time_point_cast<std::chrono::seconds> std::chrono::system_clock::now());
(std::chrono::system_clock::now());
std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); std::string msg = std::vformat(fmt.get(), std::make_format_args(args...));
std::osyncstream(std::cout) << "\033[1;33m" std::osyncstream(std::cout)
<< std::format("[WARN][{:%Y-%m-%d %H:%M:%S}]", now_time) << "\033[1;33m" << std::format("[WARN][{:%Y-%m-%d %H:%M:%S}]", now_time)
<< msg << msg << "\033[0m"
<< "\033[0m"
<< "\n"; << "\n";
} }
template <typename... Args> template <typename... Args>
inline void log(Level level, std::source_location loc, std::format_string<Args...> fmt, Args&&... args) { inline void log(Level level, std::source_location loc,
auto now_time = std::chrono:: std::format_string<Args...> fmt, Args&&... args) {
time_point_cast<std::chrono::seconds> auto now_time = std::chrono::time_point_cast<std::chrono::seconds>(
(std::chrono::system_clock::now()); std::chrono::system_clock::now());
std::string msg = std::vformat(fmt.get(), std::make_format_args(args...)); std::string msg = std::vformat(fmt.get(), std::make_format_args(args...));
switch (level) { switch (level) {
case Logger::Level::TRACE: case Logger::Level::TRACE:
std::osyncstream(std::cout) << "\033[1;34m" std::osyncstream(std::cout)
<< std::format("[TRACE][{:%Y-%m-%d %H:%M:%S}]", now_time) << "\033[1;34m"
<< "[" << loc.file_name() << ":" << loc.line() << "]" << std::format("[TRACE][{:%Y-%m-%d %H:%M:%S}]", now_time) << "["
<< "[" << loc.function_name() << "]" << loc.file_name() << ":" << loc.line() << "]"
<< msg << "[" << loc.function_name() << "]" << msg << "\033[0m"
<< "\033[0m"
<< "\n"; << "\n";
break; break;
case Logger::Level::DEBUG: case Logger::Level::DEBUG:
std::osyncstream(std::cout) << "\033[1;34m" std::osyncstream(std::cout)
<< std::format("[DEBUG][{:%Y-%m-%d %H:%M:%S}]", now_time) << "\033[1;34m"
<< msg << std::format("[DEBUG][{:%Y-%m-%d %H:%M:%S}]", now_time) << msg
<< "\033[0m" << "\033[0m"
<< "\n"; << "\n";
break; break;
@@ -90,13 +77,9 @@ namespace Logger {
case Logger::Level::ERROR: case Logger::Level::ERROR:
error(fmt, std::forward<Args>(args)...); error(fmt, std::forward<Args>(args)...);
break; break;
}
} }
} } // namespace Logger
}
}
} // namespace Cubed

View File

@@ -3,9 +3,9 @@
namespace Cubed { namespace Cubed {
namespace Math { namespace Math {
void extract_frustum_planes(const glm::mat4& mvp_matrix, std::vector<glm::vec4>& planes); void extract_frustum_planes(const glm::mat4& mvp_matrix,
std::vector<glm::vec4>& planes);
} }
} } // namespace Cubed

View File

@@ -4,19 +4,18 @@
namespace Cubed { namespace Cubed {
class PerlinNoise { class PerlinNoise {
public: public:
static void init(unsigned seed); static void init(unsigned seed);
static float noise(float x, float y, float z); static float noise(float x, float y, float z);
static void reload(unsigned seed); static void reload(unsigned seed);
private: private:
static inline std::atomic<bool> is_init = false; static inline std::atomic<bool> is_init = false;
static inline std::vector<int> p; static inline std::vector<int> p;
static float fade(float t); static float fade(float t);
static float lerp(float t, float a, float b); static float lerp(float t, float a, float b);
static float grad(int hash, float x, float y, float z); static float grad(int hash, float x, float y, float z);
}; };
} } // namespace Cubed

View File

@@ -1,14 +1,14 @@
#pragma once #pragma once
#include <glad/glad.h>
#include <SOIL2.h> #include <SOIL2.h>
#include <glad/glad.h>
#include <string> #include <string>
namespace Cubed { namespace Cubed {
namespace Tools { 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);
void print_shader_log(GLuint shader); void print_shader_log(GLuint shader);
void print_program_info(int prog); void print_program_info(int prog);
bool check_opengl_error(); bool check_opengl_error();
@@ -16,6 +16,6 @@ namespace Tools {
void delete_image_data(unsigned char* data); void delete_image_data(unsigned char* data);
unsigned char* load_image_data(const std::string& tex_image_path); unsigned char* load_image_data(const std::string& tex_image_path);
} } // namespace Tools
} } // namespace Cubed

View File

@@ -1,36 +1,39 @@
#pragma once #pragma once
#include "Cubed/tools/log.hpp"
#include <string> #include <string>
#include <Cubed/tools/log.hpp>
#ifdef _WIN32 #ifdef _WIN32
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <psapi.h> #include <psapi.h>
#include <windows.h>
typedef LONG(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); typedef LONG(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
#elif defined(__linux__) #elif defined(__linux__)
#include <fstream>
#include <sys/resource.h> #include <sys/resource.h>
#include <unistd.h> #include <unistd.h>
#include <fstream>
#endif #endif
namespace Cubed { namespace Cubed {
namespace Tools { namespace Tools {
inline bool get_os_version(std::string& str) { inline bool get_os_version(std::string& str) {
#ifdef _WIN32 #ifdef _WIN32
HMODULE hntdll = GetModuleHandleW(L"ntdll.dll"); HMODULE hntdll = GetModuleHandleW(L"ntdll.dll");
if (!hntdll) return false; if (!hntdll)
return false;
auto prtl_get_version = reinterpret_cast<RtlGetVersionPtr>( auto prtl_get_version = reinterpret_cast<RtlGetVersionPtr>(
GetProcAddress(hntdll, "RtlGetVersion")); 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); 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.dwMajorVersion == 10) {
if (osvi.dwBuildNumber >= 22000) { if (osvi.dwBuildNumber >= 22000) {
str = "Windows 11 Build " + std::to_string(osvi.dwBuildNumber); str = "Windows 11 Build " + std::to_string(osvi.dwBuildNumber);
@@ -74,7 +77,8 @@ inline bool get_os_version(std::string& str) {
inline size_t get_current_rss() { inline size_t get_current_rss() {
#ifdef _WIN32 #ifdef _WIN32
PROCESS_MEMORY_COUNTERS_EX pmc; 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 pmc.WorkingSetSize;
} }
return 0; return 0;
@@ -96,17 +100,23 @@ inline std::string get_cpu_info() {
std::string cpu_name; std::string cpu_name;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, if (RegOpenKeyExW(HKEY_LOCAL_MACHINE,
L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
0, KEY_READ, &h_key) == ERROR_SUCCESS) { KEY_READ, &h_key) == ERROR_SUCCESS) {
DWORD dw_size = 0; 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<wchar_t> buffer(dw_size / sizeof(wchar_t)); std::vector<wchar_t> buffer(dw_size / sizeof(wchar_t));
if (RegQueryValueExW(h_key, L"ProcessorNameString", NULL, NULL, (LPBYTE)buffer.data(), &dw_size) == ERROR_SUCCESS) { if (RegQueryValueExW(h_key, L"ProcessorNameString", NULL, NULL,
int len = WideCharToMultiByte(CP_UTF8, 0, buffer.data(), -1, NULL, 0, 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) { if (len > 0) {
std::vector<char> narrow(len); std::vector<char> 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(); cpu_name = narrow.data();
} }
} }
@@ -141,8 +151,6 @@ inline std::string get_cpu_info() {
#endif #endif
} }
} // namespace Tools
} } // namespace Cubed
}

View File

@@ -1,10 +1,10 @@
#pragma once #pragma once
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <glm/glm.hpp> #include <glm/glm.hpp>
namespace Cubed { namespace Cubed {
enum class Color { enum class Color {
BLACK, BLACK,
WHITE, WHITE,
@@ -55,7 +55,6 @@ inline constexpr glm::vec4 color_value(Color color) {
ASSERT_MSG(false, "Unknown Color"); ASSERT_MSG(false, "Unknown Color");
return vec4{1.0f, 1.0f, 1.0f, 1.0f}; return vec4{1.0f, 1.0f, 1.0f, 1.0f};
} }
} }
inline glm::vec4 rgb255_to_float(int r, int g, int b, int a) { 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}; return glm::vec4{nr, ng, nb, na};
} }
} } // namespace Cubed

View File

@@ -1,21 +1,20 @@
#pragma once #pragma once
#include "Cubed/primitive_data.hpp"
#include "Cubed/ui/color.hpp"
#include <glad/glad.h> #include <glad/glad.h>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <string> #include <string>
#include <Cubed/config.hpp>
#include <Cubed/primitive_data.hpp>
#include <Cubed/ui/color.hpp>
namespace Cubed { namespace Cubed {
class Shader; class Shader;
class Text { class Text {
public: public:
explicit Text(std::string_view name); 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();
Text(const Text&) = delete; Text(const Text&) = delete;
Text(Text&&) noexcept; Text(Text&&) noexcept;
@@ -50,7 +49,6 @@ private:
void update_vertices(); void update_vertices();
void upload_to_gpu(); void upload_to_gpu();
}; };
} } // namespace Cubed

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
namespace Cubed { namespace Cubed {
@@ -27,7 +28,6 @@ private:
int m_width; int m_width;
int m_height; int m_height;
Renderer& m_renderer; Renderer& m_renderer;
}; };
} } // namespace Cubed

View File

@@ -1,28 +1,22 @@
#include <Cubed/app.hpp> #include "Cubed/app.hpp"
#include <Cubed/debug_collector.hpp>
#include <Cubed/gameplay/player.hpp>
#include <Cubed/map_table.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/cubed_random.hpp>
#include <Cubed/tools/system_info.hpp>
#include <Cubed/tools/perlin_noise.hpp>
#include <imgui_impl_glfw.h> #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 <exception> #include <exception>
#include <imgui_impl_glfw.h>
namespace Cubed { 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(); ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window)); App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
@@ -35,7 +29,6 @@ void App::cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
if (!app->m_window.is_mouse_enable()) { if (!app->m_window.is_mouse_enable()) {
app->m_camera.update_cursor_position_camera(xpos, ypos); app->m_camera.update_cursor_position_camera(xpos, ypos);
} }
} }
void App::init() { void App::init() {
m_window.init(); m_window.init();
@@ -44,13 +37,18 @@ void App::init() {
glfwSetWindowUserPointer(m_window.get_glfw_window(), this); glfwSetWindowUserPointer(m_window.get_glfw_window(), this);
glfwSetCursorPosCallback(m_window.get_glfw_window(), cursor_position_callback); glfwSetCursorPosCallback(m_window.get_glfw_window(),
glfwSetMouseButtonCallback(m_window.get_glfw_window(), mouse_button_callback); cursor_position_callback);
glfwSetWindowFocusCallback(m_window.get_glfw_window(), window_focus_callback); glfwSetMouseButtonCallback(m_window.get_glfw_window(),
glfwSetWindowSizeCallback(m_window.get_glfw_window(), window_reshape_callback); 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); glfwSetKeyCallback(m_window.get_glfw_window(), key_callback);
glfwSetScrollCallback(m_window.get_glfw_window(), mouse_scroll_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); glfwSetCharCallback(m_window.get_glfw_window(), char_callback);
ChunkGenerator::init(); ChunkGenerator::init();
@@ -67,14 +65,17 @@ void App::init() {
m_dev_panel.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(); ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window)); App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr"); 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 (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_window.toggle_mouse_able();
app->m_camera.reset_camera(); app->m_camera.reset_camera();
return; return;
@@ -108,13 +109,13 @@ void App::key_callback(GLFWwindow* window, int key, int scancode, int action, in
app->m_camera.reset_camera(); app->m_camera.reset_camera();
} }
break; break;
} }
app->m_world.get_player("TestPlayer").update_player_move_state(key, action); 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(); ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window)); App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr"); ASSERT_MSG(app, "nullptr");
@@ -128,7 +129,8 @@ void App::mouse_button_callback(GLFWwindow* window, int button, int action, int
if (app->m_window.is_mouse_enable()) { if (app->m_window.is_mouse_enable()) {
app->m_window.toggle_mouse_able(); app->m_window.toggle_mouse_able();
app->m_camera.reset_camera(); app->m_camera.reset_camera();
break;; break;
;
} }
Input::get_input_state().mouse_state.left = true; Input::get_input_state().mouse_state.left = true;
} }
@@ -158,17 +160,18 @@ void App::window_focus_callback(GLFWwindow* window, int focused) {
if (focused) { if (focused) {
app->m_camera.reset_camera(); 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<App*>(glfwGetWindowUserPointer(window)); App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr"); ASSERT_MSG(app, "nullptr");
app->m_window.update_viewport(); 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(); ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window)); App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
@@ -202,8 +205,7 @@ void App::char_callback(GLFWwindow* window, unsigned int c) {
void App::render() { void App::render() {
if (glfwGetWindowAttrib(m_window.get_glfw_window(), GLFW_ICONIFIED) != 0) if (glfwGetWindowAttrib(m_window.get_glfw_window(), GLFW_ICONIFIED) != 0) {
{
ImGui_ImplGlfw_Sleep(10); ImGui_ImplGlfw_Sleep(10);
return; return;
} }
@@ -219,7 +221,6 @@ void App::run() {
update(); update();
render(); render();
} }
} }
static Gait player_gait = Gait::WALK; static Gait player_gait = Gait::WALK;
@@ -236,8 +237,11 @@ void App::update() {
glfwSetWindowTitle(m_window.get_glfw_window(), title.c_str()); glfwSetWindowTitle(m_window.get_glfw_window(), title.c_str());
frame_count = 0; frame_count = 0;
fps_time_count = 0.0f; fps_time_count = 0.0f;
DebugCollector::get().report("fps", std::string{"FPS: " + std::to_string(fps)}); DebugCollector::get().report(
DebugCollector::get().report("rss", std::format("RSS: {}mb", Tools::get_current_rss() / (1024 * 1024))); "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_texture_manager.update();
m_world.update(delta_time); m_world.update(delta_time);
@@ -253,7 +257,6 @@ void App::update() {
m_renderer.update_fov(fov + 5.0f); m_renderer.update_fov(fov + 5.0f);
} }
} }
} }
int App::start_cubed_application(int argc, char** argv) { int App::start_cubed_application(int argc, char** argv) {
@@ -271,36 +274,19 @@ int App::start_cubed_application(int argc, char** argv) {
} catch (...) { } catch (...) {
Logger::error("Unkown error"); Logger::error("Unkown error");
} }
return 1; return 1;
} }
float App::delte_time() { float App::delte_time() { return delta_time; }
return delta_time;
}
float App::get_fps() { float App::get_fps() { return fps; }
return fps;
}
Camera& App::camera() { Camera& App::camera() { return m_camera; }
return m_camera; DevPanel& App::dev_panel() { return m_dev_panel; }
} Renderer& App::renderer() { return m_renderer; }
DevPanel& App::dev_panel() { TextureManager& App::texture_manager() { return m_texture_manager; }
return m_dev_panel; Window& App::window() { return m_window; }
} World& App::world() { return m_world; }
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;
}
} } // namespace Cubed

View File

@@ -1,13 +1,11 @@
#include <Cubed/camera.hpp> #include "Cubed/camera.hpp"
#include <Cubed/gameplay/player.hpp>
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/gameplay/player.hpp"
#include "Cubed/tools/cubed_assert.hpp"
namespace Cubed { namespace Cubed {
Camera::Camera() {}
Camera::Camera() {
}
void Camera::update_move_camera() { void Camera::update_move_camera() {
ASSERT_MSG(m_player, "nullptr"); 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); m_camera_pos = glm::vec3(pos.x, pos.y + 1.6f, pos.z);
} }
void Camera::camera_init(Player* player) { void Camera::camera_init(Player* player) {
m_player = player; m_player = player;
update_move_camera(); update_move_camera();
@@ -24,13 +21,9 @@ void Camera::camera_init(Player* player) {
hot_reload(); 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) { void Camera::update_cursor_position_camera(double xpos, double ypos) {
if (m_firse_mouse) { if (m_firse_mouse) {
@@ -51,12 +44,10 @@ void Camera::update_cursor_position_camera(double xpos, double ypos) {
const glm::mat4 Camera::get_camera_lookat() const { const glm::mat4 Camera::get_camera_lookat() const {
ASSERT_MSG(m_player, "nullptr"); 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 { const glm::vec3& Camera::get_camera_pos() const { return m_camera_pos; }
return m_camera_pos;
}
} // namespace Cubed
}

View File

@@ -1,6 +1,7 @@
#include <Cubed/config.hpp> #include "Cubed/config.hpp"
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
@@ -10,22 +11,16 @@ using namespace std::string_view_literals;
namespace Cubed { namespace Cubed {
Config::Config() { Config::Config() { load_or_create_config(); }
load_or_create_config();
}
Config::~Config() { Config::~Config() { save_to_file(); }
save_to_file();
}
Config& Config::get() { Config& Config::get() {
static Config instance; static Config instance;
return instance; return instance;
} }
toml::table& Config::table() { toml::table& Config::table() { return m_tbl; }
return m_tbl;
}
void Config::create_config() { void Config::create_config() {
static constexpr auto SOURCE = R"( static constexpr auto SOURCE = R"(
@@ -60,14 +55,14 @@ void Config::create_config() {
std::abort(); std::abort();
} }
Logger::info("Create New Config File Success"); Logger::info("Create New Config File Success");
} }
void Config::load_or_create_config() { 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)) { if (!fs::is_regular_file(config_path)) {
create_config(); create_config();
} else try { } else
try {
m_tbl = toml::parse_file(config_path.string()); m_tbl = toml::parse_file(config_path.string());
} catch (const toml::parse_error& err) { } catch (const toml::parse_error& err) {
Logger::error("Load Config Error: \"{}\"", err.what()); Logger::error("Load Config Error: \"{}\"", err.what());
@@ -75,7 +70,6 @@ void Config::load_or_create_config() {
} }
Logger::info("Load Config File Success"); Logger::info("Load Config File Success");
} }
void Config::save_to_file() { void Config::save_to_file() {
@@ -121,4 +115,4 @@ toml::node_view<toml::node> Config::val_view(std::string_view key) {
return view; return view;
} }
} } // namespace Cubed

View File

@@ -1,15 +1,12 @@
#include <Cubed/debug_collector.hpp> #include "Cubed/debug_collector.hpp"
#include <Cubed/config.hpp> #include "Cubed/config.hpp"
#include <Cubed/tools/system_info.hpp> #include "Cubed/tools/cubed_hash.hpp"
#include <Cubed/tools/cubed_hash.hpp> #include "Cubed/tools/system_info.hpp"
namespace Cubed { namespace Cubed {
DebugCollector::DebugCollector() {}
DebugCollector::DebugCollector() {
}
DebugCollector& DebugCollector::get() { DebugCollector& DebugCollector::get() {
static DebugCollector instance; static DebugCollector instance;
@@ -27,70 +24,54 @@ void DebugCollector::init_text() {
Text opengl_version_text("opengl_version"); Text opengl_version_text("opengl_version");
Text biome_text("biome"); Text biome_text("biome");
Text speed_text("speed"); Text speed_text("speed");
version_text version_text.position(0.0f, 100.0f)
.position(0.0f, 100.0f)
.scale(0.8f) .scale(0.8f)
.color(Color::WHITE) .color(Color::WHITE)
.text("Version: " + Config::get().get<std::string>("version")); .text("Version: " + Config::get().get<std::string>("version"));
fps_text fps_text.position(0.0f, 50.0f).text("FPS: 0");
.position(0.0f, 50.0f) player_pos_text.position(0.0f, 150.0f)
.text("FPS: 0");
player_pos_text
.position(0.0f, 150.0f)
.scale(0.8f) .scale(0.8f)
.text("x: 0.00 y: 0.00 z: 0.00"); .text("x: 0.00 y: 0.00 z: 0.00");
rendered_chunk_text rendered_chunk_text.text("Rendered Chunk: 0")
.text("Rendered Chunk: 0")
.scale(0.8f) .scale(0.8f)
.position(0.0, 200.0f); .position(0.0, 200.0f);
rss_text rss_text.text("RSS: 0mb").scale(0.8f).position(0.0f, 300.0f);
.text("RSS: 0mb")
.scale(0.8f)
.position(0.0f, 300.0f);
std::string os; std::string os;
Text os_text("os"); Text os_text("os");
os_text os_text.scale(0.8f).position(0.0f, 250.0f);
.scale(0.8f)
.position(0.0f, 250.0f);
if (Tools::get_os_version(os)) { if (Tools::get_os_version(os)) {
os_text os_text.text("OS: " + os);
.text("OS: " + os);
Logger::info("System: {}", os); Logger::info("System: {}", os);
} else { } else {
os_text os_text.text("OS: Unknown");
.text("OS: Unknown");
} }
cpu_text cpu_text.text("CPU: " + Tools::get_cpu_info())
.text("CPU: " + Tools::get_cpu_info())
.scale(0.7f) .scale(0.7f)
.position(0.0f, 350.0f); .position(0.0f, 350.0f);
gpu_text gpu_text
.text(std::string{"GPU: "} + reinterpret_cast<const char*>(glGetString(GL_RENDERER))) .text(std::string{"GPU: "} +
reinterpret_cast<const char*>(glGetString(GL_RENDERER)))
.scale(0.7f) .scale(0.7f)
.position(0.0f, 400.0f); .position(0.0f, 400.0f);
opengl_version_text 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) .scale(0.7f)
.position(0.0f, 450.0f); .position(0.0f, 450.0f);
biome_text biome_text.text("Biome: ").scale(0.8f).position(0.0f, 500.0f);
.text("Biome: ") speed_text.text("Speed: 0 m/s").scale(0.8f).position(0.0f, 550.0f);
.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({version_text.uuid(), std::move(version_text)});
m_texts.insert({fps_text.uuid(), std::move(fps_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({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({os_text.uuid(), std::move(os_text)});
m_texts.insert({rss_text.uuid(), std::move(rss_text)}); m_texts.insert({rss_text.uuid(), std::move(rss_text)});
m_texts.insert({cpu_text.uuid(), std::move(cpu_text)}); m_texts.insert({cpu_text.uuid(), std::move(cpu_text)});
m_texts.insert({gpu_text.uuid(), std::move(gpu_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({biome_text.uuid(), std::move(biome_text)});
m_texts.insert({speed_text.uuid(), std::move(speed_text)}); m_texts.insert({speed_text.uuid(), std::move(speed_text)});
} }
@@ -111,4 +92,4 @@ void DebugCollector::report(std::string_view name, std::string_view content) {
t.text(content); t.text(content);
} }
} } // namespace Cubed

View File

@@ -1,8 +1,9 @@
#include <Cubed/dev_panel.hpp> #include "Cubed/dev_panel.hpp"
#include <Cubed/app.hpp>
#include <Cubed/gameplay/player.hpp> #include "Cubed/app.hpp"
#include <Cubed/tools/log.hpp> #include "Cubed/config.hpp"
#include <Cubed/tools/perlin_noise.hpp> #include "Cubed/gameplay/player.hpp"
#include "Cubed/tools/log.hpp"
#include <imgui.h> #include <imgui.h>
#include <imgui_impl_glfw.h> #include <imgui_impl_glfw.h>
@@ -42,11 +43,7 @@ static int filter_unsigned(ImGuiInputTextCallbackData* data) {
return 0; return 0;
} }
DevPanel::DevPanel(App& app) : DevPanel::DevPanel(App& app) : m_app(app) {}
m_app(app)
{
}
void DevPanel::init() { void DevPanel::init() {
m_player = &m_app.world().get_player("TestPlayer"); m_player = &m_app.world().get_player("TestPlayer");
@@ -64,7 +61,6 @@ void DevPanel::render() {
} }
*/ */
// Start the Dear ImGui frame // Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame(); ImGui_ImplGlfw_NewFrame();
@@ -82,12 +78,12 @@ void DevPanel::render() {
ImGui::End(); ImGui::End();
ImGui::Render(); ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
} }
void DevPanel::show_about_table_bar() { void DevPanel::show_about_table_bar() {
if (ImGui::BeginTabItem("about")) { 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::Text("Author: zhenyan121");
ImGui::Separator(); ImGui::Separator();
ImGui::Text("Libraries Used"); ImGui::Text("Libraries Used");
@@ -112,52 +108,116 @@ void DevPanel::show_biome_table_bar() {
ImGui::Text("Biome"); ImGui::Text("Biome");
if (ImGui::BeginTabBar("Biome")) { if (ImGui::BeginTabBar("Biome")) {
if (ImGui::BeginTabItem("Plain")) { if (ImGui::BeginTabItem("Plain")) {
ImGui::SliderFloat("MinTemp##plain", &plain_params().temp.first, TEMP_MIN, TEMP_MAX); ImGui::SliderFloat("MinTemp##plain", &plain_params().temp.first,
ImGui::SliderFloat("MaxTemp##plain", &plain_params().temp.second, TEMP_MIN, TEMP_MAX); TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##plain", &plain_params().humid.first, HUMID_MIN, HUMID_MAX); ImGui::SliderFloat("MaxTemp##plain", &plain_params().temp.second,
ImGui::SliderFloat("MaxHumid##plain", &plain_params().humid.second, HUMID_MIN, HUMID_MAX); TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("Freq One##plain", &plain_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); ImGui::SliderFloat("MinHumid##plain", &plain_params().humid.first,
ImGui::SliderFloat("Freq Two##plain", &plain_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq Three##plain", &plain_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); ImGui::SliderFloat("MaxHumid##plain", &plain_params().humid.second,
ImGui::SliderInt("Base Y##plain", &plain_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); HUMID_MIN, HUMID_MAX);
ImGui::SliderInt("Amplitude##plain", &plain_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_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(); ImGui::EndTabItem();
} }
if (ImGui::BeginTabItem("Forest")) { if (ImGui::BeginTabItem("Forest")) {
ImGui::SliderFloat("MinTemp##forest", &forest_params().temp.first, TEMP_MIN, TEMP_MAX); ImGui::SliderFloat("MinTemp##forest", &forest_params().temp.first,
ImGui::SliderFloat("MaxTemp##forest", &forest_params().temp.second, TEMP_MIN, TEMP_MAX); TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##forest", &forest_params().humid.first, HUMID_MIN, HUMID_MAX); ImGui::SliderFloat("MaxTemp##forest", &forest_params().temp.second,
ImGui::SliderFloat("MaxHumid##forest", &forest_params().humid.second, HUMID_MIN, HUMID_MAX); TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("Freq One##forest", &forest_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); ImGui::SliderFloat("MinHumid##forest", &forest_params().humid.first,
ImGui::SliderFloat("Freq Two##forest", &forest_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq Three##forest", &forest_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); ImGui::SliderFloat("MaxHumid##forest",
ImGui::SliderInt("Base Y##forest", &forest_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); &forest_params().humid.second, HUMID_MIN,
ImGui::SliderInt("Amplitude##forest", &forest_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX); HUMID_MAX);
ImGui::SliderFloat("Tree Freq##forest", &forest_params().tree_frequency, TREE_FREQ_MIM, TREE_FREQ_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(); ImGui::EndTabItem();
} }
if (ImGui::BeginTabItem("Desert")) { if (ImGui::BeginTabItem("Desert")) {
ImGui::SliderFloat("MinTemp##desert", &desert_params().temp.first, TEMP_MIN, TEMP_MAX); ImGui::SliderFloat("MinTemp##desert", &desert_params().temp.first,
ImGui::SliderFloat("MaxTemp##desert", &desert_params().temp.second, TEMP_MIN, TEMP_MAX); TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##desert", &desert_params().humid.first, HUMID_MIN, HUMID_MAX); ImGui::SliderFloat("MaxTemp##desert", &desert_params().temp.second,
ImGui::SliderFloat("MaxHumid##desert", &desert_params().humid.second, HUMID_MIN, HUMID_MAX); TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("Freq One##desert", &desert_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); ImGui::SliderFloat("MinHumid##desert", &desert_params().humid.first,
ImGui::SliderFloat("Freq Two##desert", &desert_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq Three##desert", &desert_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); ImGui::SliderFloat("MaxHumid##desert",
ImGui::SliderInt("Base Y##desert", &desert_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); &desert_params().humid.second, HUMID_MIN,
ImGui::SliderInt("Amplitude##desert", &desert_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX); 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(); ImGui::EndTabItem();
} }
if (ImGui::BeginTabItem("Mountain")) { if (ImGui::BeginTabItem("Mountain")) {
ImGui::SliderFloat("MinTemp##mountain", &mountain_params().temp.first, TEMP_MIN, TEMP_MAX); ImGui::SliderFloat("MinTemp##mountain",
ImGui::SliderFloat("MaxTemp##mountain", &mountain_params().temp.second, TEMP_MIN, TEMP_MAX); &mountain_params().temp.first, TEMP_MIN,
ImGui::SliderFloat("MinHumid##mountain", &mountain_params().humid.first, HUMID_MIN, HUMID_MAX); TEMP_MAX);
ImGui::SliderFloat("MaxHumid##mountain", &mountain_params().humid.second, HUMID_MIN, HUMID_MAX); ImGui::SliderFloat("MaxTemp##mountain",
ImGui::SliderFloat("Freq One##mountain", &mountain_params().frequencies[0], FREQ1_MIN, FREQ1_MAX); &mountain_params().temp.second, TEMP_MIN,
ImGui::SliderFloat("Freq Two##mountain", &mountain_params().frequencies[1], FREQ2_MIN, FREQ2_MAX); TEMP_MAX);
ImGui::SliderFloat("Freq Three##mountain", &mountain_params().frequencies[2], FREQ3_MIN, FREQ3_MAX); ImGui::SliderFloat("MinHumid##mountain",
ImGui::SliderInt("Base Y##mountain", &mountain_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX); &mountain_params().humid.first, HUMID_MIN,
ImGui::SliderInt("Amplitude##mountain", &mountain_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX); 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::EndTabItem();
} }
ImGui::EndTabBar(); ImGui::EndTabBar();
@@ -176,18 +236,23 @@ void DevPanel::show_settings_tab_item() {
Config::get().set("player.fov", static_cast<double>(m_config.fov)); Config::get().set("player.fov", static_cast<double>(m_config.fov));
m_app.renderer().hot_reload(); m_app.renderer().hot_reload();
} }
if (ImGui::SliderFloat("Sensitivity", &m_config.mouse_sensitivity, 0.01f, 1.0f)) { if (ImGui::SliderFloat("Sensitivity", &m_config.mouse_sensitivity,
Config::get().set("player.mouse_sensitivity", static_cast<double>(m_config.mouse_sensitivity)); 0.01f, 1.0f)) {
Config::get().set("player.mouse_sensitivity",
static_cast<double>(m_config.mouse_sensitivity));
m_player->hot_reload(); m_player->hot_reload();
} }
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("default##2")) { if (ImGui::Button("default##2")) {
m_config.mouse_sensitivity = 0.15f; m_config.mouse_sensitivity = 0.15f;
Config::get().set("player.mouse_sensitivity", static_cast<double>(m_config.mouse_sensitivity)); Config::get().set("player.mouse_sensitivity",
static_cast<double>(m_config.mouse_sensitivity));
m_player->hot_reload(); m_player->hot_reload();
} }
if (ImGui::SliderInt("Distance", &m_config.rendering_distance, 2, 128)) { if (ImGui::SliderInt("Distance", &m_config.rendering_distance, 2,
Config::get().set("world.rendering_distance", m_config.rendering_distance); 128)) {
Config::get().set("world.rendering_distance",
m_config.rendering_distance);
m_app.world().hot_reload(); m_app.world().hot_reload();
} }
if (ImGui::Checkbox("Fullscreen", &m_config.fullscreen)) { if (ImGui::Checkbox("Fullscreen", &m_config.fullscreen)) {
@@ -211,16 +276,17 @@ void DevPanel::show_settings_tab_item() {
} else { } else {
m_config.aniso = 1; m_config.aniso = 1;
} }
} }
if (m_config.is_enable_aniso) { if (m_config.is_enable_aniso) {
ImGui::SameLine(); ImGui::SameLine();
if (!m_config.is_support_aniso) { if (!m_config.is_support_aniso) {
ImGui::Text("Not Support\n"); ImGui::Text("Not Support\n");
} else { } 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; m_config.is_reload = false;
int log = static_cast<int>(std::log2(m_config.aniso) + 0.5f); int log =
static_cast<int>(std::log2(m_config.aniso) + 0.5f);
m_config.aniso = static_cast<int>(std::pow(2, log)); m_config.aniso = static_cast<int>(std::pow(2, log));
if (m_config.aniso < 2) { if (m_config.aniso < 2) {
m_config.aniso = 2; m_config.aniso = 2;
@@ -254,22 +320,21 @@ void DevPanel::show_settings_tab_item() {
ImGui::EndTabItem(); ImGui::EndTabItem();
} }
} }
void DevPanel::show_world_tab_item() { void DevPanel::show_world_tab_item() {
if (ImGui::BeginTabItem("world")) { if (ImGui::BeginTabItem("world")) {
if (m_text_editing.perlin_seed) { if (m_text_editing.perlin_seed) {
if (ImGui::InputText("Perlin Noise Seed", perlin_noise_input_buffer, sizeof(perlin_noise_input_buffer), if (ImGui::InputText("Perlin Noise Seed", perlin_noise_input_buffer,
sizeof(perlin_noise_input_buffer),
ImGuiInputTextFlags_CallbackCharFilter | ImGuiInputTextFlags_CallbackCharFilter |
ImGuiInputTextFlags_EnterReturnsTrue, ImGuiInputTextFlags_EnterReturnsTrue,
filter_unsigned)) filter_unsigned)) {
{ ChunkGenerator::seed(static_cast<unsigned int>(
ChunkGenerator::seed(static_cast<unsigned int>(std::strtoul(perlin_noise_input_buffer, nullptr, 10))); std::strtoul(perlin_noise_input_buffer, nullptr, 10)));
m_text_editing.perlin_seed = false; m_text_editing.perlin_seed = false;
m_player->set_player_pos({0.0f, 255.0f, 0.0f}); m_player->set_player_pos({0.0f, 255.0f, 0.0f});
m_app.world().rebuild_world(); m_app.world().rebuild_world();
} }
} }
if (!m_text_editing.perlin_seed) { if (!m_text_editing.perlin_seed) {
@@ -306,7 +371,8 @@ void DevPanel::show_player_tab_item() {
return; return;
} }
if (ImGui::BeginTabItem("player")) { 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) { if (m_player_profile.game_mode == 0) {
m_player->change_mode(GameMode::CREATIVE); m_player->change_mode(GameMode::CREATIVE);
} else if (m_player_profile.game_mode == 1) { } 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 (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) { if (m_player_profile.gait == 0) {
m_player->gait() = Gait::WALK; m_player->gait() = Gait::WALK;
} else if (m_player_profile.gait == 1) { } else if (m_player_profile.gait == 1) {
@@ -329,19 +396,26 @@ void DevPanel::show_player_tab_item() {
ImGui::DragFloat3("##player_pos", m_player_profile.pos); ImGui::DragFloat3("##player_pos", m_player_profile.pos);
ImGui::SameLine(); ImGui::SameLine();
if (ImGui::Button("TP")) { 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("Acceleration", &m_player->acceleration(), 1.0f,
ImGui::SliderFloat("Deceleration", &m_player->deceleration(), 1.0f, 200.0f); 200.0f);
ImGui::SliderFloat("Deceleration", &m_player->deceleration(), 1.0f,
200.0f);
if (m_player->game_mode() == GameMode::CREATIVE) { if (m_player->game_mode() == GameMode::CREATIVE) {
m_player_profile.game_mode = 0; m_player_profile.game_mode = 0;
ImGui::SliderFloat("MaxWalkSpeed", &m_player->max_walk_speed(), 1.0f, 200.0f); ImGui::SliderFloat("MaxWalkSpeed", &m_player->max_walk_speed(),
ImGui::SliderFloat("MaxRunSpeed", &m_player->max_run_speed(), 1.0f, 500.0f); 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); ImGui::SliderFloat("G", &m_player->g(), 1.0f, 200.0f);
} else if (m_player->game_mode() == GameMode::SPECTATOR) { } else if (m_player->game_mode() == GameMode::SPECTATOR) {
m_player_profile.game_mode = 1; 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")) { if (ImGui::Button("reset")) {
m_player->max_walk_speed() = DEFAULT_MAX_WALK_SPEED; m_player->max_walk_speed() = DEFAULT_MAX_WALK_SPEED;
@@ -360,19 +434,21 @@ void DevPanel::show_player_tab_item() {
m_player_profile.gait = 1; m_player_profile.gait = 1;
} }
ImGui::EndTabItem(); ImGui::EndTabItem();
} }
} }
void DevPanel::update_config_view() { void DevPanel::update_config_view() {
auto config = Config::get(); auto config = Config::get();
m_config.fov = static_cast<float>(config.val_view("player.fov").value_or(70.0)); m_config.fov =
static_cast<float>(config.val_view("player.fov").value_or(70.0));
m_config.fullscreen = config.val_view("window.fullscreen").value_or(false); 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.v_sync = config.val_view("window.V-Sync").value_or(true);
m_config.mouse_sensitivity = static_cast<float>(config.val_view("player.mouse_sensitivity").value_or(0.15)); m_config.mouse_sensitivity = static_cast<float>(
config.val_view("player.mouse_sensitivity").value_or(0.15));
m_config.width = config.val_view("window.width").value_or(800); m_config.width = config.val_view("window.width").value_or(800);
m_config.height = config.val_view("window.height").value_or(600); 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); m_theme = config.val_view("devpanel.theme").value_or(0);
if (m_theme != 1 && m_theme != 0) { if (m_theme != 1 && m_theme != 0) {
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()); m_player_profile.game_mode = std::to_underlying(m_player->game_mode());
} }
} } // namespace Cubed

View File

@@ -1,54 +1,40 @@
#include <Cubed/gameplay/biome.hpp> #include "Cubed/gameplay/biome.hpp"
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <Cubed/tools/perlin_noise.hpp> #include "Cubed/tools/log.hpp"
#include "Cubed/tools/perlin_noise.hpp"
#include <cmath> #include <cmath>
#include <unordered_map> #include <unordered_map>
namespace Cubed { namespace Cubed {
static PlainParams plain { static PlainParams plain{{Biome::PLAIN,
{
Biome::PLAIN,
{0.0f, 0.5f}, {0.0f, 0.5f},
{0.0f, 0.5f}, {0.0f, 0.5f},
{0.003f, 0.010f, 0.020f}, {0.003f, 0.010f, 0.020f},
{62, 8} {62, 8}}};
}
};
static ForestParams forest { static ForestParams forest{{Biome::FOREST,
{
Biome::FOREST,
{0.5f, 1.0f}, {0.5f, 1.0f},
{0.5f, 1.0f}, {0.5f, 1.0f},
{0.004f, 0.010f, 0.020f}, {0.004f, 0.010f, 0.020f},
{64, 12} {64, 12}},
},
0.1f 0.1f
}; };
static DesertParams desert { static DesertParams desert{{Biome::DESERT,
{
Biome::DESERT,
{0.5f, 1.0f}, {0.5f, 1.0f},
{0.0f, 0.5f}, {0.0f, 0.5f},
{0.003f, 0.010f, 0.020f}, {0.003f, 0.010f, 0.020f},
{61, 12} {61, 12}}};
}
};
static MountainParams mountain { static MountainParams mountain{{Biome::MOUNTAIN,
{
Biome::MOUNTAIN,
{0.0f, 0.5f}, {0.0f, 0.5f},
{0.5f, 1.0f}, {0.5f, 1.0f},
{0.006f, 0.014f, 0.010f}, {0.006f, 0.014f, 0.010f},
{70, 70} {70, 70}}};
}
};
std::string get_biome_str(Biome biome) { std::string get_biome_str(Biome biome) {
std::string str; std::string str;
@@ -93,16 +79,20 @@ Biome get_biome_from_noise(float temp, float humid) {
*/ */
Biome get_biome_from_noise(float temp, float humid) { Biome get_biome_from_noise(float temp, float humid) {
using enum Biome; 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; 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; 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; 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; return MOUNTAIN;
} }
Logger::warn("Invail Temp {} or Humid {}", temp, humid); Logger::warn("Invail Temp {} or Humid {}", temp, humid);
@@ -149,18 +139,15 @@ BiomeHeightRange get_biome_height_range(Biome biome) {
Biome safe_int_to_biome(int x) { Biome safe_int_to_biome(int x) {
using enum Biome; using enum Biome;
static const std::unordered_map<int, Biome> INT_TO_BIOME_MAP{ static const std::unordered_map<int, Biome> INT_TO_BIOME_MAP{
{0, PLAIN}, {0, PLAIN}, {1, FOREST}, {2, DESERT}, {3, MOUNTAIN}};
{1, FOREST},
{2, DESERT},
{3, MOUNTAIN}
};
auto it = INT_TO_BIOME_MAP.find(x); 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; 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 { auto weight = [](float t, float h, float ct, float ch) -> float {
float dt = t - ct; float dt = t - ct;
@@ -181,38 +168,31 @@ int get_interpolated_height(float world_x, float world_z, float temp, float humi
w_forest = std::pow(w_forest, pow_n) * FOREST_FREQ; w_forest = std::pow(w_forest, pow_n) * FOREST_FREQ;
float total = w_mountain + w_plain + w_desert + w_forest; 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 sample_height = [&](Biome b) -> float {
auto range = get_biome_height_range(b); auto range = get_biome_height_range(b);
auto [f1, f2, f3] = get_noise_frequencies_for_biome(b); auto [f1, f2, f3] = get_noise_frequencies_for_biome(b);
float n = float n = 1.00f * PerlinNoise::noise(world_x * f1, 0.5f, world_z * f1) +
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.50f * PerlinNoise::noise(world_x * f2, 0.5f, world_z * f2) +
0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3); 0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3);
n /= 1.75f; n /= 1.75f;
return range.base_y + n * range.amplitude; return range.base_y + n * range.amplitude;
}; };
float h = w_mountain * sample_height(Biome::MOUNTAIN) float h = w_mountain * sample_height(Biome::MOUNTAIN) +
+ w_plain * sample_height(Biome::PLAIN) w_plain * sample_height(Biome::PLAIN) +
+ w_desert * sample_height(Biome::DESERT) w_desert * sample_height(Biome::DESERT) +
+ w_forest * sample_height(Biome::FOREST); w_forest * sample_height(Biome::FOREST);
return static_cast<int>(h); return static_cast<int>(h);
} }
PlainParams& plain_params() { PlainParams& plain_params() { return plain; }
return plain; ForestParams& forest_params() { return forest; }
} DesertParams& desert_params() { return desert; }
ForestParams& forest_params() { MountainParams& mountain_params() { return mountain; }
return forest;
}
DesertParams& desert_params() {
return desert;
}
MountainParams& mountain_params() {
return mountain;
}
}
} // namespace Cubed

View File

@@ -1,47 +1,37 @@
#include <Cubed/gameplay/chunk.hpp> #include "Cubed/gameplay/chunk.hpp"
#include <Cubed/gameplay/world.hpp>
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/gameplay/world.hpp"
#include <Cubed/tools/cubed_random.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <Cubed/tools/log.hpp> #include "Cubed/tools/log.hpp"
#include <Cubed/tools/math_tools.hpp>
#include <Cubed/tools/perlin_noise.hpp>
#include <utility> #include <utility>
namespace Cubed { namespace Cubed {
Chunk::Chunk(World& world, ChunkPos chunk_pos) : Chunk::Chunk(World& world, ChunkPos chunk_pos)
m_chunk_pos(chunk_pos), : m_chunk_pos(chunk_pos), m_world(world) {}
m_world(world)
{
}
Chunk::~Chunk() { Chunk::~Chunk() {
if (m_vbo != 0) { if (m_vbo != 0) {
m_world.push_delete_vbo(m_vbo); m_world.push_delete_vbo(m_vbo);
} }
} }
Chunk::Chunk(Chunk&& other) noexcept : Chunk::Chunk(Chunk&& other) noexcept
m_dirty(other.is_dirty()), : m_dirty(other.is_dirty()), m_need_upload(other.m_need_upload.load()),
m_need_upload(other.m_need_upload.load()),
m_is_on_gen_vertex_data(other.m_is_on_gen_vertex_data.load()), m_is_on_gen_vertex_data(other.m_is_on_gen_vertex_data.load()),
m_vertex_sum(other.m_vertex_sum.load()), m_vertex_sum(other.m_vertex_sum.load()), m_biome(other.m_biome.load()),
m_biome(other.m_biome.load()), m_chunk_pos(std::move(other.m_chunk_pos)), m_world(other.m_world),
m_chunk_pos(std::move(other.m_chunk_pos)),
m_world(other.m_world),
m_heightmap(std::move(other.m_heightmap)), m_heightmap(std::move(other.m_heightmap)),
m_blocks(std::move(other.m_blocks)), m_blocks(std::move(other.m_blocks)), m_vbo(other.m_vbo),
m_vbo(other.m_vbo), m_vertexs_data(std::move(other.m_vertexs_data)) {
m_vertexs_data(std::move(other.m_vertexs_data))
{
other.m_vbo = 0; other.m_vbo = 0;
} }
Chunk& Chunk::operator=(Chunk&& other) noexcept { 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<const void*>(&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<const void*>(&other));
m_vbo = other.m_vbo; m_vbo = other.m_vbo;
other.m_vbo = 0; other.m_vbo = 0;
m_chunk_pos = std::move(other.m_chunk_pos); m_chunk_pos = std::move(other.m_chunk_pos);
@@ -56,26 +46,24 @@ Chunk& Chunk::operator=(Chunk&& other) noexcept {
return *this; return *this;
} }
Biome Chunk::get_biome() const { Biome Chunk::get_biome() const { return m_biome.load(); }
return m_biome.load();
}
ChunkPos Chunk::get_chunk_pos() const { ChunkPos Chunk::get_chunk_pos() const { return m_chunk_pos; }
return m_chunk_pos;
}
const std::vector<uint8_t>& Chunk::get_chunk_blocks() const{ const std::vector<uint8_t>& Chunk::get_chunk_blocks() const { return m_blocks; }
return m_blocks;
}
HeightMapArray Chunk::get_heightmap() const { HeightMapArray Chunk::get_heightmap() const {
//Logger::info("Chunk pos {} {} in get_heightmap this {}", m_chunk_pos.x, m_chunk_pos.z, static_cast<const void*>(this)); // Logger::info("Chunk pos {} {} in get_heightmap this {}", m_chunk_pos.x,
// m_chunk_pos.z, static_cast<const void*>(this));
return m_heightmap; return m_heightmap;
} }
int Chunk::get_index(int x, int y, int z) { 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)); ASSERT(!(x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
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) { 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); Logger::error("block pos x {} y {} z {} range error", x, y, z);
ASSERT(0); ASSERT(0);
} }
@@ -86,7 +74,8 @@ int Chunk::get_index(const glm::vec3& pos) {
return Chunk::get_index(pos.x, pos.y, pos.z); return Chunk::get_index(pos.x, pos.y, pos.z);
} }
void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& neighbor_block) { void Chunk::gen_vertex_data(
const std::array<const std::vector<uint8_t>*, 4>& neighbor_block) {
if (m_is_on_gen_vertex_data) { if (m_is_on_gen_vertex_data) {
return; return;
} }
@@ -94,9 +83,8 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
std::lock_guard lk(m_vertexs_data_mutex); std::lock_guard lk(m_vertexs_data_mutex);
m_vertexs_data.clear(); m_vertexs_data.clear();
static const glm::ivec3 DIR[6] = { static const glm::ivec3 DIR[6] = {{0, 0, 1}, {1, 0, 0}, {0, 0, -1},
{0,0,1},{1,0,0},{0,0,-1},{-1,0,0},{0,1,0},{0,-1,0} {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}};
};
for (int x = 0; x < SIZE_X; x++) { for (int x = 0; x < SIZE_X; x++) {
for (int y = 0; y < SIZE_Y; y++) { for (int y = 0; y < SIZE_Y; y++) {
@@ -116,15 +104,18 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
int nz = z + DIR[face].z; int nz = z + DIR[face].z;
bool neighbor_cull = false; 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_nx = world_x + DIR[face].x;
int world_ny = world_y + DIR[face].y; int world_ny = world_y + DIR[face].y;
int world_nz = world_z + DIR[face].z; int world_nz = world_z + DIR[face].z;
auto [neighbor_x, neighbor_z] = World::chunk_pos(world_nx, world_nz); auto [neighbor_x, neighbor_z] =
World::chunk_pos(world_nx, world_nz);
auto is_cull = [&](const std::vector<uint8_t>* chunk_blocks){ auto is_cull =
[&](const std::vector<uint8_t>* chunk_blocks) {
if (chunk_blocks == nullptr) { if (chunk_blocks == nullptr) {
return false; return false;
} }
@@ -132,13 +123,16 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
y = world_ny; y = world_ny;
x = world_nx - neighbor_x * CHUCK_SIZE; x = world_nx - neighbor_x * CHUCK_SIZE;
z = world_nz - neighbor_z * 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) { if (x < 0 || y < 0 || z < 0 ||
x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE) {
return false; return false;
} }
int idx = Chunk::get_index(x, y, z); int idx = Chunk::get_index(x, y, z);
// not init // not init
if (static_cast<size_t>(idx) >= chunk_blocks->size()) { if (static_cast<size_t>(idx) >=
chunk_blocks->size()) {
Logger::warn("not init"); Logger::warn("not init");
return false; return false;
} }
@@ -164,7 +158,8 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
} else if (m_chunk_pos.z - 1 == neighbor_z) { } else if (m_chunk_pos.z - 1 == neighbor_z) {
neighbor_cull = is_cull(neighbor_block[3]); 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 { } else {
auto id = m_blocks[get_index(nx, ny, nz)]; auto id = m_blocks[get_index(nx, ny, nz)];
if (!is_in_transparent_map(id)) { if (!is_in_transparent_map(id)) {
@@ -195,7 +190,6 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
} }
} }
} }
} }
} }
m_vertex_sum = m_vertexs_data.size(); m_vertex_sum = m_vertexs_data.size();
@@ -203,9 +197,7 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
m_is_on_gen_vertex_data = false; m_is_on_gen_vertex_data = false;
} }
GLuint Chunk::get_vbo() const{ GLuint Chunk::get_vbo() const { return m_vbo; }
return m_vbo;
}
size_t Chunk::get_vertex_sum() const { size_t Chunk::get_vertex_sum() const {
if (m_vertex_sum == 0) { if (m_vertex_sum == 0) {
@@ -214,7 +206,6 @@ size_t Chunk::get_vertex_sum() const {
return m_vertex_sum.load(); return m_vertex_sum.load();
} }
void Chunk::gen_phase_one() { void Chunk::gen_phase_one() {
m_generator = std::make_unique<ChunkGenerator>(*this); m_generator = std::make_unique<ChunkGenerator>(*this);
if (!m_generator) { if (!m_generator) {
@@ -240,7 +231,8 @@ void Chunk::gen_phase_three() {
m_generator->generate_heightmap(); m_generator->generate_heightmap();
} }
void Chunk::gen_phase_four(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) { void Chunk::gen_phase_four(
const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) {
if (!m_generator) { if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr"); Logger::error("ChunkGenerator is Nullptr");
return; return;
@@ -256,7 +248,8 @@ void Chunk::gen_phase_five() {
m_generator->generate_terrain_blocks(); m_generator->generate_terrain_blocks();
} }
void Chunk::gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) { void Chunk::gen_phase_six(
const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) {
if (!m_generator) { if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr"); Logger::error("ChunkGenerator is Nullptr");
return; return;
@@ -282,54 +275,35 @@ void Chunk::upload_to_gpu() {
} }
std::lock_guard lk(m_vertexs_data_mutex); std::lock_guard lk(m_vertexs_data_mutex);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo); 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); glBindBuffer(GL_ARRAY_BUFFER, 0);
// after fininshed it, can use // after fininshed it, can use
clear_dirty(); clear_dirty();
m_need_upload = false; m_need_upload = false;
} }
bool Chunk::is_dirty() const{ bool Chunk::is_dirty() const { return m_dirty.load(); }
return m_dirty.load();
}
void Chunk::mark_dirty() { void Chunk::mark_dirty() { m_dirty = true; }
m_dirty = true;
}
void Chunk::clear_dirty() { void Chunk::clear_dirty() { m_dirty = false; }
m_dirty = false;
}
bool Chunk::is_need_upload() const { bool Chunk::is_need_upload() const { return m_need_upload.load(); }
return m_need_upload.load();
}
void Chunk::need_upload() { void Chunk::need_upload() { m_need_upload = true; }
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; m_blocks[index] = id;
mark_dirty(); mark_dirty();
} }
ChunkPos Chunk::chunk_pos() const{ ChunkPos Chunk::chunk_pos() const { return m_chunk_pos; }
return m_chunk_pos;
}
Biome Chunk::biome() const{ Biome Chunk::biome() const { return m_biome; }
return m_biome;
}
void Chunk::biome(Biome b) { void Chunk::biome(Biome b) { m_biome = b; }
m_biome = b;
}
HeightMapArray& Chunk::heightmap() { HeightMapArray& Chunk::heightmap() { return m_heightmap; }
return m_heightmap; std::vector<uint8_t>& Chunk::blocks() { return m_blocks; }
} } // namespace Cubed
std::vector<uint8_t>& Chunk::blocks() {
return m_blocks;
}
}

View File

@@ -1,16 +1,14 @@
#include <Cubed/gameplay/chunk_generator.hpp> #include "Cubed/gameplay/chunk_generator.hpp"
#include <Cubed/gameplay/chunk.hpp> #include "Cubed/gameplay/chunk.hpp"
#include <Cubed/gameplay/tree.hpp> #include "Cubed/gameplay/tree.hpp"
#include <Cubed/tools/cubed_hash.hpp> #include "Cubed/tools/cubed_hash.hpp"
#include <Cubed/tools/perlin_noise.hpp> #include "Cubed/tools/perlin_noise.hpp"
#include <numeric> #include <numeric>
namespace Cubed { namespace Cubed {
ChunkGenerator::ChunkGenerator(Chunk& chunk) : ChunkGenerator::ChunkGenerator(Chunk& chunk) : m_chunk(chunk) {
m_chunk(chunk)
{
ASSERT_MSG(is_init, "ChunksGenerator is not init"); ASSERT_MSG(is_init, "ChunksGenerator is not init");
ChunkPos pos = m_chunk.get_chunk_pos(); ChunkPos pos = m_chunk.get_chunk_pos();
unsigned seed = HASH::mix_hash(pos.x, pos.z, m_generator_seed); unsigned seed = HASH::mix_hash(pos.x, pos.z, m_generator_seed);
@@ -33,26 +31,26 @@ void ChunkGenerator::reload() {
is_seed_change = false; is_seed_change = false;
} }
const unsigned& ChunkGenerator::seed() { const unsigned& ChunkGenerator::seed() { return m_generator_seed; }
return m_generator_seed;
}
void ChunkGenerator::seed(unsigned s) { void ChunkGenerator::seed(unsigned s) {
is_seed_change = true; is_seed_change = true;
m_generator_seed = s; m_generator_seed = s;
} }
void ChunkGenerator::assign_chunk_biome() { void ChunkGenerator::assign_chunk_biome() {
auto m_chunk_pos = m_chunk.chunk_pos(); auto m_chunk_pos = m_chunk.chunk_pos();
float x = static_cast<float>(m_chunk_pos.x); float x = static_cast<float>(m_chunk_pos.x);
float z = static_cast<float>(m_chunk_pos.z); float z = static_cast<float>(m_chunk_pos.z);
float temp = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 0.0f, z * BIOME_NOISE_FREQUENCY); float temp = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 0.0f,
float humid = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 1.0f, z * BIOME_NOISE_FREQUENCY); 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); auto biome = get_biome_from_noise(temp, humid);
m_chunk.biome(biome); m_chunk.biome(biome);
} }
void ChunkGenerator::resolve_biome_adjacency_conflict(const std::array<const Chunk*, 4>& adj_chunks) { void ChunkGenerator::resolve_biome_adjacency_conflict(
const std::array<const Chunk*, 4>& adj_chunks) {
auto m_biome = m_chunk.biome(); auto m_biome = m_chunk.biome();
for (auto& chunk : adj_chunks) { for (auto& chunk : adj_chunks) {
if (chunk == nullptr) { if (chunk == nullptr) {
@@ -89,10 +87,12 @@ void ChunkGenerator::generate_heightmap() {
auto sample_height = [&](Biome b) -> float { auto sample_height = [&](Biome b) -> float {
auto range = get_biome_height_range(b); auto range = get_biome_height_range(b);
auto [f1, f2, f3] = get_noise_frequencies_for_biome(b); auto [f1, f2, f3] = get_noise_frequencies_for_biome(b);
float n = float n = 1.00f * PerlinNoise::noise(world_x * f1, 0.5f,
1.00f * PerlinNoise::noise(world_x * f1, 0.5f, world_z * f1) + world_z * f1) +
0.50f * PerlinNoise::noise(world_x * f2, 0.5f, world_z * f2) + 0.50f * PerlinNoise::noise(world_x * f2, 0.5f,
0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3); world_z * f2) +
0.25f * PerlinNoise::noise(world_x * f3, 0.5f,
world_z * f3);
n /= 1.75f; n /= 1.75f;
return range.base_y + n * range.amplitude; return range.base_y + n * range.amplitude;
}; };
@@ -101,7 +101,8 @@ void ChunkGenerator::generate_heightmap() {
} }
} }
void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) { void ChunkGenerator::blend_heightmap_boundaries(
const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) {
auto& m_heightmap = m_chunk.heightmap(); auto& m_heightmap = m_chunk.heightmap();
// Width of interpolation influence (in number of cells) // Width of interpolation influence (in number of cells)
@@ -119,8 +120,11 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
int dist = (SIZE_X - 1) - x; // distance from right border int dist = (SIZE_X - 1) - x; // distance from right border
if (dist < BLEND_RADIUS) { if (dist < BLEND_RADIUS) {
// Neighbor's boundary row is its x=0 column // Neighbor's boundary row is its x=0 column
float neighbor_h = static_cast<float>((*neighbor_heightmap[0])[0][z]); float neighbor_h =
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; // larger weight when closer static_cast<float>((*neighbor_heightmap[0])[0][z]);
float t =
1.0f - static_cast<float>(dist) /
BLEND_RADIUS; // larger weight when closer
// Use smoothstep for a more natural transition // Use smoothstep for a more natural transition
t = t * t * (3.0f - 2.0f * t); t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h; blended += t * neighbor_h;
@@ -132,7 +136,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
if (neighbor_heightmap[1] != std::nullopt) { if (neighbor_heightmap[1] != std::nullopt) {
int dist = x; // distance from left border int dist = x; // distance from left border
if (dist < BLEND_RADIUS) { if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[1])[SIZE_X - 1][z]); float neighbor_h = static_cast<float>(
(*neighbor_heightmap[1])[SIZE_X - 1][z]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h; blended += t * neighbor_h;
@@ -144,7 +149,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
if (neighbor_heightmap[2] != std::nullopt) { if (neighbor_heightmap[2] != std::nullopt) {
int dist = (SIZE_Z - 1) - z; int dist = (SIZE_Z - 1) - z;
if (dist < BLEND_RADIUS) { if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[2])[x][0]); float neighbor_h =
static_cast<float>((*neighbor_heightmap[2])[x][0]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h; blended += t * neighbor_h;
@@ -156,7 +162,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
if (neighbor_heightmap[3] != std::nullopt) { if (neighbor_heightmap[3] != std::nullopt) {
int dist = z; int dist = z;
if (dist < BLEND_RADIUS) { if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[3])[x][SIZE_Z - 1]); float neighbor_h = static_cast<float>(
(*neighbor_heightmap[3])[x][SIZE_Z - 1]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h; blended += t * neighbor_h;
@@ -196,7 +203,6 @@ void ChunkGenerator::generate_terrain_blocks() {
} else { } else {
m_blocks[Chunk::get_index(x, y, z)] = 2; m_blocks[Chunk::get_index(x, y, z)] = 2;
} }
} }
if (height > 110) { if (height > 110) {
m_blocks[Chunk::get_index(x, height - 1, z)] = 3; 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<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) { void ChunkGenerator::blend_surface_blocks_borders(
const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) {
auto& m_blocks = m_chunk.blocks(); auto& m_blocks = m_chunk.blocks();
auto& m_heightmap = m_chunk.heightmap(); auto& m_heightmap = m_chunk.heightmap();
constexpr int BLEND_RADIUS = 12; constexpr int BLEND_RADIUS = 12;
constexpr int WORLD_HEIGHT = WORLD_SIZE_Y; constexpr int WORLD_HEIGHT = WORLD_SIZE_Y;
// Helper lambda: get top block type from a neighbor's block data at (nx, nz) // Helper lambda: get top block type from a neighbor's block data at (nx,
auto get_top_block_from_neighbor = [&](const std::vector<uint8_t>& blocks, int nx, int nz) -> uint8_t { // nz)
auto get_top_block_from_neighbor = [&](const std::vector<uint8_t>& blocks,
int nx, int nz) -> uint8_t {
// Search from topmost y downwards for the first non-zero block // Search from topmost y downwards for the first non-zero block
for (int y = WORLD_HEIGHT - 1; y >= 0; --y) { for (int y = WORLD_HEIGHT - 1; y >= 0; --y) {
int idx = Chunk::get_index(nx, y, nz); // linear index: y * area + z * size + x int idx = Chunk::get_index(
if (idx >= 0 && idx < static_cast<int>(blocks.size()) && blocks[idx] != 0) { nx, y, nz); // linear index: y * area + z * size + x
if (idx >= 0 && idx < static_cast<int>(blocks.size()) &&
blocks[idx] != 0) {
return blocks[idx]; return blocks[idx];
} }
} }
@@ -247,7 +258,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
top_y = m_heightmap[x][z]; top_y = m_heightmap[x][z];
type_self = m_blocks[Chunk::get_index(x, top_y, z)]; type_self = m_blocks[Chunk::get_index(x, top_y, z)];
if (top_y == -1) continue; // no block? skip if (top_y == -1)
continue; // no block? skip
// Weight map: type -> total weight // Weight map: type -> total weight
std::unordered_map<uint8_t, float> weights; std::unordered_map<uint8_t, float> weights;
@@ -259,7 +271,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); // smoothstep t = t * t * (3.0f - 2.0f * t); // smoothstep
if (t > 0.0f) { 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; weights[type_neighbor] += t;
} }
} }
@@ -270,7 +283,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) { 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; weights[type_neighbor] += t;
} }
} }
@@ -281,7 +295,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) { 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; weights[type_neighbor] += t;
} }
} }
@@ -292,7 +307,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) { 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; weights[type_neighbor] += t;
} }
} }
@@ -337,14 +353,12 @@ void ChunkGenerator::generate_vegetation() {
for (auto x : x_arr) { for (auto x : x_arr) {
for (auto z : z_arr) { for (auto z : z_arr) {
if (m_random.random_bool(forest_params().tree_frequency)) { if (m_random.random_bool(forest_params().tree_frequency)) {
build_tree(m_chunk, {x, static_cast<int>(m_heightmap[x][z]), z}); build_tree(m_chunk,
{x, static_cast<int>(m_heightmap[x][z]), z});
} }
} }
} }
} }
} }
} // namespace Cubed
}

View File

@@ -1,65 +1,48 @@
#include <Cubed/gameplay/player.hpp> #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 <Cubed/debug_collector.hpp>
#include <Cubed/gameplay/world.hpp>
#include <Cubed/map_table.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
namespace Cubed { namespace Cubed {
Player::Player(World& world, const std::string& name) : Player::Player(World& world, const std::string& name)
m_name(name), : m_name(name), m_world(world) {
m_world(world)
{
hot_reload(); hot_reload();
} }
Player::~Player() { Player::~Player() {}
}
AABB Player::get_aabb() const { AABB Player::get_aabb() const {
float half_width = m_size.x / 2.0f; float half_width = m_size.x / 2.0f;
float half_depth = m_size.z / 2.0f; float half_depth = m_size.z / 2.0f;
glm::vec3 min{ glm::vec3 min{m_player_pos.x - half_width, m_player_pos.y,
m_player_pos.x - half_width, m_player_pos.z - half_depth};
m_player_pos.y,
m_player_pos.z - half_depth
};
glm::vec3 max { glm::vec3 max{m_player_pos.x + half_width, m_player_pos.y + m_size.y,
m_player_pos.x + half_width, m_player_pos.z + half_depth};
m_player_pos.y + m_size.y,
m_player_pos.z + half_depth
};
return AABB{min, max}; return AABB{min, max};
} }
const glm::vec3& Player::get_front() const { const glm::vec3& Player::get_front() const { return m_front; }
return m_front;
}
const Gait& Player::get_gait() const { const Gait& Player::get_gait() const { return m_gait; }
return m_gait;
}
const std::optional<LookBlock>& Player::get_look_block_pos() const { const std::optional<LookBlock>& Player::get_look_block_pos() const {
return m_look_block; return m_look_block;
} }
const glm::vec3& Player::get_player_pos() const { const glm::vec3& Player::get_player_pos() const { return m_player_pos; }
return m_player_pos;
}
const MoveState& Player::get_move_state() const { const MoveState& Player::get_move_state() const { return m_move_state; }
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); glm::vec3 dir = glm::normalize(front);
// float step = 0.1f; // float step = 0.1f;
glm::ivec3 cur = glm::floor(start); glm::ivec3 cur = glm::floor(start);
@@ -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); normal = glm::vec3(0.0f, 0.0f, -step_z);
iz += step_z; iz += step_z;
} }
} }
return false; return false;
} }
@@ -147,13 +128,11 @@ void Player::change_mode(GameMode mode) {
void Player::hot_reload() { void Player::hot_reload() {
auto& config = Config::get(); auto& config = Config::get();
m_sensitivity = static_cast<float>(config.get<double>("player.mouse_sensitivity")); m_sensitivity =
static_cast<float>(config.get<double>("player.mouse_sensitivity"));
} }
void Player::set_player_pos(const glm::vec3& pos) { void Player::set_player_pos(const glm::vec3& pos) { m_player_pos = pos; }
m_player_pos = pos;
}
void Player::update(float delta_time) { void Player::update(float delta_time) {
@@ -163,10 +142,11 @@ void Player::update(float delta_time) {
DebugCollector::get().report("player_pos", DebugCollector::get().report("player_pos",
std::format("x: {:.2f} y: {:.2f} z: {:.2f}", std::format("x: {:.2f} y: {:.2f} z: {:.2f}",
m_player_pos.x, m_player_pos.y, m_player_pos.z 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)); DebugCollector::get().report("speed",
std::format("Speed: {:.2} m/s", m_xz_speed));
} }
void Player::update_player_move_state(int key, int action) { void Player::update_player_move_state(int key, int action) {
@@ -180,7 +160,6 @@ void Player::update_player_move_state(int key, int action) {
if (m_game_mode != SPECTATOR) { if (m_game_mode != SPECTATOR) {
m_gait = Gait::WALK; m_gait = Gait::WALK;
} }
} }
break; break;
case GLFW_KEY_S: case GLFW_KEY_S:
@@ -256,9 +235,10 @@ void Player::update_front_vec(float offset_x, float offset_y) {
m_yaw = std::fmod(m_yaw, 360.0); m_yaw = std::fmod(m_yaw, 360.0);
if (m_pitch > 89.0f) m_pitch = 89.0f; if (m_pitch > 89.0f)
if (m_pitch < -89.0f) 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.x = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
m_front.y = sin(glm::radians(m_pitch)); m_front.y = sin(glm::radians(m_pitch));
@@ -276,10 +256,9 @@ void Player::check_player_chunk_transition() {
if (chunk == nullptr) { if (chunk == nullptr) {
DebugCollector::get().report("biome", "Biome: Unknown"); DebugCollector::get().report("biome", "Biome: Unknown");
} else { } else {
DebugCollector::get() DebugCollector::get().report(
.report("biome", "Biome: " + get_biome_str(chunk->get_biome())); "biome", "Biome: " + get_biome_str(chunk->get_biome()));
} }
} }
} }
@@ -291,15 +270,12 @@ void Player::update_direction() {
glm::vec3 move_dir = glm::vec3(0.0f); glm::vec3 move_dir = glm::vec3(0.0f);
if (m_move_state.forward) { if (m_move_state.forward) {
move_dir_front += glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z)); move_dir_front += glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z));
} }
if (m_move_state.back) { if (m_move_state.back) {
move_dir_front -= glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z)); move_dir_front -= glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z));
} }
if (m_move_state.left) { if (m_move_state.left) {
move_dir_right -= glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z)); move_dir_right -= glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z));
} }
if (m_move_state.right) { if (m_move_state.right) {
move_dir_right += glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z)); move_dir_right += glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z));
@@ -315,7 +291,9 @@ void Player::update_lookup_block() {
// calculate the block that is looked // calculate the block that is looked
glm::ivec3 block_pos; glm::ivec3 block_pos;
glm::vec3 block_normal; 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)}; m_look_block = LookBlock{block_pos, glm::floor(block_normal)};
} else { } else {
m_look_block = std::nullopt; m_look_block = std::nullopt;
@@ -325,7 +303,6 @@ void Player::update_lookup_block() {
if (Input::get_input_state().mouse_state.left) { if (Input::get_input_state().mouse_state.left) {
if (m_world.is_block(m_look_block->pos)) { if (m_world.is_block(m_look_block->pos)) {
m_world.set_block(m_look_block->pos, 0); m_world.set_block(m_look_block->pos, 0);
} }
Input::get_input_state().mouse_state.left = false; Input::get_input_state().mouse_state.left = false;
} }
@@ -335,15 +312,16 @@ void Player::update_lookup_block() {
auto x = near_pos.x; auto x = near_pos.x;
auto y = near_pos.y; auto y = near_pos.y;
auto z = near_pos.z; auto z = near_pos.z;
AABB block_box = { AABB block_box = {glm::vec3{static_cast<float>(x),
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)}, static_cast<float>(y),
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)} static_cast<float>(z)},
}; glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
AABB player_box = get_aabb(); AABB player_box = get_aabb();
if (!player_box.intersects(block_box)) { if (!player_box.intersects(block_box)) {
m_world.set_block(near_pos, 1); m_world.set_block(near_pos, 1);
} }
} }
Input::get_input_state().mouse_state.right = false; Input::get_input_state().mouse_state.right = false;
} }
@@ -373,7 +351,8 @@ void Player::update_move(float delta_time) {
} }
// calculate speed // 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); direction = glm::vec3(0.0f, 0.0f, 0.0f);
m_xz_speed += m_acceleration * delta_time; m_xz_speed += m_acceleration * delta_time;
if (m_xz_speed > m_max_speed) { if (m_xz_speed > m_max_speed) {
@@ -389,7 +368,8 @@ void Player::update_move(float delta_time) {
update_direction(); 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 (is_fly) {
if (m_move_state.up) { if (m_move_state.up) {
@@ -407,7 +387,6 @@ void Player::update_move(float delta_time) {
if (m_move_state.up && can_up) { if (m_move_state.up && can_up) {
m_y_speed = 7.5; m_y_speed = 7.5;
can_up = false; can_up = false;
} }
m_y_speed += -m_g * delta_time; m_y_speed += -m_g * delta_time;
@@ -425,7 +404,6 @@ void Player::update_move(float delta_time) {
Logger::warn("y is tow low"); Logger::warn("y is tow low");
m_player_pos += glm::vec3(1.0f, 100.0f, 1.0f); m_player_pos += glm::vec3(1.0f, 100.0f, 1.0f);
} }
} }
void Player::update_x_move() { void Player::update_x_move() {
@@ -445,10 +423,12 @@ void Player::update_x_move() {
for (int y = miny; y <= maxy; ++y) { for (int y = miny; y <= maxy; ++y) {
for (int z = minz; z <= maxz; ++z) { for (int z = minz; z <= maxz; ++z) {
if (m_world.is_block(glm::vec3{x, y, z})) { if (m_world.is_block(glm::vec3{x, y, z})) {
AABB block_box = { AABB block_box = {glm::vec3{static_cast<float>(x),
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)}, static_cast<float>(y),
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)} static_cast<float>(z)},
}; glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
if (player_box.intersects(block_box)) { if (player_box.intersects(block_box)) {
m_gait = Gait::WALK; m_gait = Gait::WALK;
m_player_pos.x -= move_distance.x; 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 y = miny; y <= maxy; ++y) {
for (int z = minz; z <= maxz; ++z) { for (int z = minz; z <= maxz; ++z) {
if (m_world.is_block(glm::vec3{x, y, z})) { if (m_world.is_block(glm::vec3{x, y, z})) {
AABB block_box = { AABB block_box = {glm::vec3{static_cast<float>(x),
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)}, static_cast<float>(y),
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)} static_cast<float>(z)},
}; glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
if (player_box.intersects(block_box)) { if (player_box.intersects(block_box)) {
m_player_pos.y -= move_distance.y; m_player_pos.y -= move_distance.y;
m_y_speed = 0.0f; m_y_speed = 0.0f;
@@ -513,10 +495,12 @@ void Player::update_z_move() {
for (int y = miny; y <= maxy; ++y) { for (int y = miny; y <= maxy; ++y) {
for (int z = minz; z <= maxz; ++z) { for (int z = minz; z <= maxz; ++z) {
if (m_world.is_block(glm::vec3{x, y, z})) { if (m_world.is_block(glm::vec3{x, y, z})) {
AABB block_box = { AABB block_box = {glm::vec3{static_cast<float>(x),
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)}, static_cast<float>(y),
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)} static_cast<float>(z)},
}; glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
if (player_box.intersects(block_box)) { if (player_box.intersects(block_box)) {
m_gait = Gait::WALK; m_gait = Gait::WALK;
m_player_pos.z -= move_distance.z; m_player_pos.z -= move_distance.z;
@@ -542,29 +526,13 @@ void Player::update_scroll(double yoffset) {
} }
} }
float& Player::max_walk_speed() { float& Player::max_walk_speed() { return m_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::max_run_speed() { float& Player::acceleration() { return m_acceleration; }
return m_max_run_speed; float& Player::deceleration() { return m_deceleration; }
} float& Player::g() { return m_g; }
float& Player::max_speed() { Gait& Player::gait() { return m_gait; }
return m_max_speed; GameMode& Player::game_mode() { return m_game_mode; }
}
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

View File

@@ -1,77 +1,30 @@
#include <Cubed/gameplay/tree.hpp> #include "Cubed/gameplay/tree.hpp"
#include <Cubed/gameplay/chunk.hpp> #include "Cubed/gameplay/chunk.hpp"
#include <array> #include <array>
namespace Cubed { namespace Cubed {
using glm::ivec3; using glm::ivec3;
static constexpr std::array<TreeStructNode, 62> TREE{{ static constexpr std::array<TreeStructNode, 62> TREE{{
{{0, 1, 0}, 5}, {{0, 1, 0}, 5}, {{0, 2, 0}, 5}, {{0, 3, 0}, 5}, {{0, 4, 0}, 5},
{{0, 2, 0}, 5}, {{0, 5, 0}, 5}, {{0, 6, 0}, 6}, {{0, 5, 1}, 6}, {{1, 5, 0}, 6},
{{0, 3, 0}, 5}, {{0, 5, -1}, 6}, {{-1, 5, 0}, 6}, {{1, 5, 1}, 6}, {{1, 5, -1}, 6},
{{0, 4, 0}, 5}, {{-1, 5, -1}, 6}, {{-1, 5, 1}, 6}, {{0, 4, 1}, 6}, {{1, 4, 0}, 6},
{{0, 5, 0}, 5}, {{0, 4, -1}, 6}, {{-1, 4, 0}, 6}, {{1, 4, 1}, 6}, {{1, 4, -1}, 6},
{{0, 6, 0}, 6}, {{-1, 4, -1}, 6}, {{-1, 4, 1}, 6}, {{0, 4, 2}, 6}, {{2, 4, 0}, 6},
{{0, 5, 1}, 6}, {{0, 4, -2}, 6}, {{-2, 4, 0}, 6}, {{2, 4, 2}, 6}, {{2, 4, -2}, 6},
{{1, 5, 0}, 6}, {{-2, 4, -2}, 6}, {{-2, 4, 2}, 6}, {{1, 4, 2}, 6}, {{2, 4, 1}, 6},
{{0, 5, -1}, 6}, {{-1, 4, 2}, 6}, {{2, 4, -1}, 6}, {{1, 4, -2}, 6}, {{-2, 4, 1}, 6},
{{-1, 5, 0}, 6}, {{-1, 4, -2}, 6}, {{-2, 4, -1}, 6}, {{0, 3, 1}, 6}, {{1, 3, 0}, 6},
{{1, 5, 1}, 6}, {{0, 3, -1}, 6}, {{-1, 3, 0}, 6}, {{1, 3, 1}, 6}, {{1, 3, -1}, 6},
{{1, 5, -1}, 6}, {{-1, 3, -1}, 6}, {{-1, 3, 1}, 6}, {{0, 3, 2}, 6}, {{2, 3, 0}, 6},
{{-1, 5, -1}, 6}, {{0, 3, -2}, 6}, {{-2, 3, 0}, 6}, {{2, 3, 2}, 6}, {{2, 3, -2}, 6},
{{-1, 5, 1}, 6}, {{-2, 3, -2}, 6}, {{-2, 3, 2}, 6}, {{1, 3, 2}, 6}, {{2, 3, 1}, 6},
{{0, 4, 1}, 6}, {{-1, 3, 2}, 6}, {{2, 3, -1}, 6}, {{1, 3, -2}, 6}, {{-2, 3, 1}, 6},
{{1, 4, 0}, 6}, {{-1, 3, -2}, 6}, {{-2, 3, -1}, 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) { bool build_tree(Chunk& chunk, const glm::ivec3& pos) {
@@ -86,7 +39,8 @@ bool build_tree(Chunk& chunk, const glm::ivec3& pos) {
int x = tree_node.x; int x = tree_node.x;
int y = tree_node.y; int y = tree_node.y;
int z = tree_node.z; int z = tree_node.z;
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; return false;
} }
if (block[Chunk::get_index(tree_node)] != 0) { if (block[Chunk::get_index(tree_node)] != 0) {
@@ -100,4 +54,4 @@ bool build_tree(Chunk& chunk, const glm::ivec3& pos) {
return true; return true;
} }
} } // namespace Cubed

View File

@@ -1,29 +1,24 @@
#include <Cubed/gameplay/world.hpp> #include "Cubed/gameplay/world.hpp"
#include <Cubed/debug_collector.hpp> #include "Cubed/config.hpp"
#include <Cubed/gameplay/player.hpp> #include "Cubed/debug_collector.hpp"
#include <Cubed/map_table.hpp> #include "Cubed/gameplay/player.hpp"
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <Cubed/tools/cubed_hash.hpp> #include "Cubed/tools/cubed_hash.hpp"
#include <Cubed/tools/math_tools.hpp> #include "Cubed/tools/math_tools.hpp"
#include <Cubed/tools/perlin_noise.hpp>
#include <execution> #include <execution>
namespace Cubed { namespace Cubed {
static constexpr ChunkPos CHUNK_DIR[] { static constexpr ChunkPos CHUNK_DIR[]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
{1, 0}, {-1, 0}, {0, 1}, {0, -1}
};
struct ChunkRenderData { struct ChunkRenderData {
std::array<const std::vector<uint8_t>*, 4> neighbor_block; std::array<const std::vector<uint8_t>*, 4> neighbor_block;
Chunk* chunk; Chunk* chunk;
}; };
World::World() { World::World() {}
}
World::~World() { World::~World() {
stop_gen_thread(); 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<LookBlock>&
} World::get_look_block_pos(const std::string& name) const {
const std::optional<LookBlock>& World::get_look_block_pos(const std::string& name) const{
static std::optional<LookBlock> null_look_block = std::nullopt; static std::optional<LookBlock> null_look_block = std::nullopt;
auto it = m_players.find(HASH::str(name)); auto it = m_players.find(HASH::str(name));
if (it == m_players.end()) { if (it == m_players.end()) {
@@ -52,7 +45,6 @@ const std::optional<LookBlock>& World::get_look_block_pos(const std::string& nam
} }
return it->second.get_look_block_pos(); return it->second.get_look_block_pos();
} }
const Chunk* World::get_chunk(const ChunkPos& pos) const { const Chunk* World::get_chunk(const ChunkPos& pos) const {
@@ -88,7 +80,8 @@ void World::init_world() {
} }
} }
Logger::info("Max Support Thread is {}", std::thread::hardware_concurrency()); Logger::info("Max Support Thread is {}",
std::thread::hardware_concurrency());
init_chunks(); init_chunks();
auto t2 = std::chrono::system_clock::now(); auto t2 = std::chrono::system_clock::now();
auto d = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); auto d = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
@@ -108,8 +101,8 @@ void World::init_chunks() {
chunk_ptrs.push_back(&chunk); chunk_ptrs.push_back(&chunk);
} }
std::for_each(std::execution::par, chunk_ptrs.begin(), chunk_ptrs.end(), [](auto& chunk){ std::for_each(std::execution::par, chunk_ptrs.begin(), chunk_ptrs.end(),
chunk->init_chunk(); [](auto& chunk){ chunk->init_chunk();
}); });
std::atomic<int> sync{0}; std::atomic<int> sync{0};
@@ -131,9 +124,8 @@ void World::init_chunks() {
} }
pending_gen_data.emplace_back(std::move(data)); pending_gen_data.emplace_back(std::move(data));
} }
std::for_each(std::execution::par, pending_gen_data.begin(), pending_gen_data.end(), [](ChunkRenderData& data){ std::for_each(std::execution::par, pending_gen_data.begin(),
if(!data.chunk) { pending_gen_data.end(), [](ChunkRenderData& data){ if(!data.chunk) { return ;
return ;
} }
data.chunk->gen_vertex_data(data.neighbor_block); data.chunk->gen_vertex_data(data.neighbor_block);
}); });
@@ -159,7 +151,6 @@ void World::init_chunks() {
continue; continue;
} }
neighbor_chunks[i] = &it->second; neighbor_chunks[i] = &it->second;
} }
chunks.gen_phase_two(neighbor_chunks); chunks.gen_phase_two(neighbor_chunks);
} }
@@ -177,7 +168,6 @@ void World::init_chunks() {
continue; continue;
} }
neighbor_chunk_heightmap[i] = it->second.get_heightmap(); neighbor_chunk_heightmap[i] = it->second.get_heightmap();
} }
chunks.gen_phase_four(neighbor_chunk_heightmap); chunks.gen_phase_four(neighbor_chunk_heightmap);
} }
@@ -195,7 +185,6 @@ void World::init_chunks() {
continue; continue;
} }
neighbor_block[i] = it->second.get_chunk_blocks(); neighbor_block[i] = it->second.get_chunk_blocks();
} }
chunks.gen_phase_six(neighbor_block); chunks.gen_phase_six(neighbor_block);
} }
@@ -221,7 +210,8 @@ void World::init_chunks() {
} }
pending_gen_data.emplace_back(std::move(data)); pending_gen_data.emplace_back(std::move(data));
} }
std::for_each(std::execution::par, pending_gen_data.begin(), pending_gen_data.end(), [](ChunkRenderData& data){ std::for_each(std::execution::par, pending_gen_data.begin(),
pending_gen_data.end(), [](ChunkRenderData& data) {
if (!data.chunk) { if (!data.chunk) {
return; return;
} }
@@ -230,9 +220,7 @@ void World::init_chunks() {
for (auto& chunk_map : m_chunks) { for (auto& chunk_map : m_chunks) {
auto& [chunk_pos, chunk] = chunk_map; auto& [chunk_pos, chunk] = chunk_map;
chunk.upload_to_gpu(); chunk.upload_to_gpu();
} }
} }
void World::render(const glm::mat4& mvp_matrix) { void World::render(const glm::mat4& mvp_matrix) {
@@ -242,9 +230,12 @@ void World::render(const glm::mat4& mvp_matrix) {
if (is_aabb_in_frustum(snapshot.center, snapshot.half_extents)) { if (is_aabb_in_frustum(snapshot.center, snapshot.half_extents)) {
glBindBuffer(GL_ARRAY_BUFFER, snapshot.vbo); glBindBuffer(GL_ARRAY_BUFFER, snapshot.vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, s)); (void*)0);
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, layer)); 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(0);
glEnableVertexAttribArray(1); glEnableVertexAttribArray(1);
@@ -253,13 +244,10 @@ void World::render(const glm::mat4& mvp_matrix) {
glDrawArrays(GL_TRIANGLES, 0, snapshot.vertex_count); glDrawArrays(GL_TRIANGLES, 0, snapshot.vertex_count);
glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0);
rendered_sum++; 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) { ChunkPos World::chunk_pos(int world_x, int world_z) {
@@ -304,7 +292,8 @@ void World::gen_chunks_internal() {
ConstChunkMap new_chunks_neighbor; ConstChunkMap new_chunks_neighbor;
// affected neighbor // affected neighbor
ChunkPtrUpdateList 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<const std::vector<uint8_t>*, 4> neighbor_block; std::array<const std::vector<uint8_t>*, 4> neighbor_block;
// build new chunk, but the neighbor in m_chunks also need to re-build // build new chunk, but the neighbor in m_chunks also need to re-build
@@ -323,7 +312,6 @@ void World::gen_chunks_internal() {
continue; continue;
} }
neighbor_chunks[i] = it->second; neighbor_chunks[i] = it->second;
} }
chunks.gen_phase_two(neighbor_chunks); chunks.gen_phase_two(neighbor_chunks);
} }
@@ -384,7 +372,8 @@ void World::gen_chunks_internal() {
chunk.gen_vertex_data(neighbor_block); chunk.gen_vertex_data(neighbor_block);
} }
m_chunk_gen_fraction = 0.7f; 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; m_chunk_gen_fraction = 0.8f;
for (auto& [pos, chunk] : affected_neighbor) { for (auto& [pos, chunk] : affected_neighbor) {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
@@ -404,7 +393,6 @@ void World::gen_chunks_internal() {
for (auto& x : new_chunks) { for (auto& x : new_chunks) {
m_new_chunk_queue.emplace_back(std::move(x)); m_new_chunk_queue.emplace_back(std::move(x));
} }
} }
m_chunk_gen_fraction = 1.0f; m_chunk_gen_fraction = 1.0f;
} }
@@ -422,7 +410,6 @@ void World::compute_required_chunks(ChunkPosSet& required_chunks) {
int z = std::floor(player_pos.z); int z = std::floor(player_pos.z);
auto [chunk_x, chunk_z] = chunk_pos(x, z); auto [chunk_x, chunk_z] = chunk_pos(x, z);
required_chunks.reserve(m_rendering_distance * m_rendering_distance); required_chunks.reserve(m_rendering_distance * m_rendering_distance);
int half = m_rendering_distance / 2; int half = m_rendering_distance / 2;
for (int u = chunk_x - half; u <= chunk_x + half; ++u) { for (int u = chunk_x - half; u <= chunk_x + half; ++u) {
@@ -432,7 +419,9 @@ void World::compute_required_chunks(ChunkPosSet& required_chunks) {
} }
} }
void World::sync_and_collect_missing_chunks(std::vector<ChunkPos>& need_gen_chunks_pos, const ChunkPosSet& required_chunks) { void World::sync_and_collect_missing_chunks(
std::vector<ChunkPos>& need_gen_chunks_pos,
const ChunkPosSet& required_chunks) {
std::lock_guard lk(m_chunks_mutex); 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()) { if (required_chunks.find(it->first) == required_chunks.end()) {
@@ -450,7 +439,9 @@ void World::sync_and_collect_missing_chunks(std::vector<ChunkPos>& 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); std::lock_guard lk(m_chunks_mutex);
for (auto& [pos, chunk] : new_chunks) { 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); std::lock_guard lk(m_chunks_mutex);
for (auto& [pos, chunk] : affected_neighbor) { for (auto& [pos, chunk] : affected_neighbor) {
for (auto& dir : CHUNK_DIR) { for (auto& dir : CHUNK_DIR) {
@@ -525,7 +517,8 @@ void World::need_gen() {
m_gen_cv.notify_one(); 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) { for (const auto& plane : m_planes) {
// distance // distance
float d = glm::dot(glm::vec3(plane), center) + plane.w; float d = glm::dot(glm::vec3(plane), center) + plane.w;
@@ -553,11 +546,11 @@ int World::get_block(const glm::ivec3& block_pos) const {
y = block_pos.y; y = block_pos.y;
x = block_pos.x - chunk_x * CHUCK_SIZE; x = block_pos.x - chunk_x * CHUCK_SIZE;
z = block_pos.z - chunk_z * 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 0;
} }
return chunk_blocks[Chunk::get_index(x, y, z)]; 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 {
@@ -573,7 +566,8 @@ bool World::is_block(const glm::ivec3& block_pos) const{
y = block_pos.y; y = block_pos.y;
x = block_pos.x - chunk_x * CHUCK_SIZE; x = block_pos.x - chunk_x * CHUCK_SIZE;
z = block_pos.z - chunk_z * 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; return false;
} }
auto id = chunk_blocks[Chunk::get_index(x, y, z)]; auto id = chunk_blocks[Chunk::get_index(x, y, z)];
@@ -603,15 +597,15 @@ void World::set_block(const glm::ivec3& block_pos, unsigned id) {
y = world_y; y = world_y;
x = world_x - chunk_x * CHUCK_SIZE; x = world_x - chunk_x * CHUCK_SIZE;
z = world_z - chunk_z * 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) { if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE) {
return; return;
} }
it->second.set_chunk_block(Chunk::get_index(x, y, z), id); it->second.set_chunk_block(Chunk::get_index(x, y, z), id);
static const glm::ivec3 NEIGHBOR_DIRS[] = { 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) { for (const auto& dir : NEIGHBOR_DIRS) {
glm::ivec3 neighbor = block_pos + dir; glm::ivec3 neighbor = block_pos + dir;
@@ -620,11 +614,8 @@ void World::set_block(const glm::ivec3& block_pos, unsigned id) {
auto it = m_chunks.find({cx, cz}); auto it = m_chunks.find({cx, cz});
if (it != m_chunks.end()) { if (it != m_chunks.end()) {
it->second.mark_dirty(); it->second.mark_dirty();
} }
} }
} }
void World::update(float delta_time) { void World::update(float delta_time) {
@@ -684,15 +675,17 @@ void World::update(float delta_time) {
if (chunk.is_need_upload()) { if (chunk.is_need_upload()) {
chunk.upload_to_gpu(); chunk.upload_to_gpu();
} }
m_render_snapshots.push_back({ m_render_snapshots.push_back(
chunk.get_vbo(), {chunk.get_vbo(), chunk.get_vertex_sum(),
chunk.get_vertex_sum(), glm::vec3(static_cast<float>(pos.x * CHUCK_SIZE) +
glm::vec3(static_cast<float>(pos.x * CHUCK_SIZE) + static_cast<float>(CHUCK_SIZE / 2), static_cast<float>(WORLD_SIZE_Y/ 2), static_cast<float>(pos.z * CHUCK_SIZE) + static_cast<float>(CHUCK_SIZE / 2)), static_cast<float>(CHUCK_SIZE / 2),
glm::vec3(static_cast<float>(CHUCK_SIZE / 2), static_cast<float>(WORLD_SIZE_Y / 2), static_cast<float>(CHUCK_SIZE / 2)) static_cast<float>(WORLD_SIZE_Y / 2),
static_cast<float>(pos.z * CHUCK_SIZE) +
static_cast<float>(CHUCK_SIZE / 2)),
glm::vec3(static_cast<float>(CHUCK_SIZE / 2),
static_cast<float>(WORLD_SIZE_Y / 2),
static_cast<float>(CHUCK_SIZE / 2))});
} }
);
}
} }
} }
} }
@@ -727,19 +720,14 @@ void World::rebuild_world() {
need_gen(); need_gen();
m_is_rebuilding = false; m_is_rebuilding = false;
} }
float World::chunk_gen_fraction() const { float World::chunk_gen_fraction() const { return m_chunk_gen_fraction.load(); }
return m_chunk_gen_fraction.load();
}
int World::rendering_distance() const { int World::rendering_distance() const { return m_rendering_distance.load(); }
return m_rendering_distance.load();
}
void World::rendering_distance(int rendering_distance) { void World::rendering_distance(int rendering_distance) {
m_rendering_distance = rendering_distance; m_rendering_distance = rendering_distance;
} }
} } // namespace Cubed

View File

@@ -1,17 +1,13 @@
#include <Cubed/input.hpp> #include "Cubed/input.hpp"
#include <Cubed/tools/cubed_assert.hpp>
namespace Cubed {
namespace Cubed {
static InputState input_state; static InputState input_state;
namespace Input { namespace Input {
InputState& get_input_state() { InputState& get_input_state() { return input_state; }
return input_state;
}
} } // namespace Input
} // namespace Cubed
}

View File

@@ -1,4 +1,4 @@
#include <Cubed/app.hpp> #include "Cubed/app.hpp"
int main(int argc, char** argv) { int main(int argc, char** argv) {
@@ -7,5 +7,3 @@ int main(int argc, char** argv) {
return Cubed::App::start_cubed_application(argc, argv); return Cubed::App::start_cubed_application(argc, argv);
} }

View File

@@ -1,17 +1,18 @@
#include <Cubed/map_table.hpp> #include "Cubed/map_table.hpp"
#include <Cubed/gameplay/block.hpp>
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/gameplay/block.hpp"
#include <Cubed/tools/cubed_hash.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_hash.hpp"
namespace Cubed { namespace Cubed {
std::unordered_map<unsigned, std::string> MapTable::id_to_name_map; std::unordered_map<unsigned, std::string> MapTable::id_to_name_map;
std::unordered_map<size_t, unsigned> MapTable::name_to_id_map; std::unordered_map<size_t, unsigned> MapTable::name_to_id_map;
const std::string& MapTable::get_name_from_id(unsigned id) { const std::string& MapTable::get_name_from_id(unsigned id) {
auto it = id_to_name_map.find(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; return it->second;
} }
unsigned MapTable::get_id_from_name(const std::string& name) { 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]; id_to_name_map[i] = BLOCK_REISTER[i];
name_to_id_map[HASH::str(BLOCK_REISTER[i])] = i; name_to_id_map[HASH::str(BLOCK_REISTER[i])] = i;
} }
}
} }
} // namespace Cubed

View File

@@ -1,33 +1,28 @@
#include <Cubed/app.hpp> #include "Cubed/renderer.hpp"
#include <Cubed/camera.hpp>
#include <Cubed/config.hpp> #include "Cubed/camera.hpp"
#include <Cubed/dev_panel.hpp> #include "Cubed/config.hpp"
#include <Cubed/primitive_data.hpp> #include "Cubed/debug_collector.hpp"
#include <Cubed/debug_collector.hpp> #include "Cubed/dev_panel.hpp"
#include <Cubed/gameplay/player.hpp> #include "Cubed/gameplay/player.hpp"
#include <Cubed/gameplay/world.hpp> #include "Cubed/gameplay/world.hpp"
#include <Cubed/texture_manager.hpp> #include "Cubed/primitive_data.hpp"
#include <Cubed/renderer.hpp> #include "Cubed/texture_manager.hpp"
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <Cubed/tools/cubed_hash.hpp> #include "Cubed/tools/cubed_hash.hpp"
#include <Cubed/tools/font.hpp> #include "Cubed/tools/font.hpp"
#include <Cubed/tools/log.hpp> #include "Cubed/tools/log.hpp"
#include <Cubed/tools/shader_tools.hpp> #include "Cubed/tools/shader_tools.hpp"
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
#include <glm/gtc/type_ptr.hpp>
#include <format> #include <format>
#include <glm/gtc/type_ptr.hpp>
namespace Cubed { namespace Cubed {
Renderer::Renderer(const Camera& camera, World& world, const TextureManager& texture_manager, DevPanel& dev_panel): Renderer::Renderer(const Camera& camera, World& world,
m_camera(camera), const TextureManager& texture_manager, DevPanel& dev_panel)
m_dev_panel(dev_panel), : m_camera(camera), m_dev_panel(dev_panel),
m_texture_manager(texture_manager), m_texture_manager(texture_manager), m_world(world) {}
m_world(world)
{
}
Renderer::~Renderer() { Renderer::~Renderer() {
glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0);
@@ -51,13 +46,19 @@ void Renderer::init() {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
Logger::info("OpenGL Version: {}.{}", GLVersion.major, GLVersion.minor); Logger::info("OpenGL Version: {}.{}", GLVersion.major, GLVersion.minor);
Logger::info("Renderer: {}", reinterpret_cast<const char*>(glGetString(GL_RENDERER))); Logger::info("Renderer: {}",
reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
Shader world_shader{"world", "shaders/block_v_shader.glsl", "shaders/block_f_shader.glsl"}; Shader world_shader{"world", "shaders/block_v_shader.glsl",
Shader outline_shader{"outline", "shaders/outline_v_shader.glsl", "shaders/outline_f_shader.glsl"}; "shaders/block_f_shader.glsl"};
Shader sky_shdaer{"sky", "shaders/sky_v_shader.glsl", "shaders/sky_f_shader.glsl"}; Shader outline_shader{"outline", "shaders/outline_v_shader.glsl",
Shader ui_shdaer{"ui", "shaders/ui_v_shader.glsl", "shaders/ui_f_shader.glsl"}; "shaders/outline_f_shader.glsl"};
Shader text_shdaer{"text", "shaders/text_v_shader.glsl", "shaders/text_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({world_shader.hash(), std::move(world_shader)});
m_shaders.insert({outline_shader.hash(), std::move(outline_shader)}); m_shaders.insert({outline_shader.hash(), std::move(outline_shader)});
@@ -73,9 +74,13 @@ void Renderer::init() {
#ifdef DEBUG_MODE #ifdef DEBUG_MODE
glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback([](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* user_param) { glDebugMessageCallback(
Logger::log(Logger::Level::DEBUG, std::source_location::current(),"GL Debug: {}", reinterpret_cast<const char*>(message)); [](GLenum source, GLenum type, GLuint id, GLenum severity,
}, nullptr); GLsizei length, const GLchar* message, const void* user_param) {
Logger::log(Logger::Level::DEBUG, std::source_location::current(),
"GL Debug: {}", reinterpret_cast<const char*>(message));
},
nullptr);
#endif #endif
m_vao.resize(NUM_VAO); m_vao.resize(NUM_VAO);
@@ -88,26 +93,24 @@ void Renderer::init() {
glGenBuffers(1, &m_outline_indices_vbo); glGenBuffers(1, &m_outline_indices_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 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); glGenBuffers(1, &m_sky_vbo);
glBindBuffer(GL_ARRAY_BUFFER, 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); glGenBuffers(1, &m_ui_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo);
for (int i = 0; i < 6; i++) { for (int i = 0; i < 6; i++) {
Vertex2D vex { Vertex2D vex{SQUARE_VERTICES[i][0], SQUARE_VERTICES[i][1],
SQUARE_VERTICES[i][0], SQUARE_TEXTURE_POS[i][0], SQUARE_TEXTURE_POS[i][1], 0};
SQUARE_VERTICES[i][1],
SQUARE_TEXTURE_POS[i][0],
SQUARE_TEXTURE_POS[i][1],
0
};
m_ui.emplace_back(vex); 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); glGenBuffers(1, &m_text_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_text_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_text_vbo);
@@ -159,7 +162,8 @@ void Renderer::render_outline() {
const auto& block_pos = m_world.get_look_block_pos("TestPlayer"); const auto& block_pos = m_world.get_look_block_pos("TestPlayer");
if (block_pos != std::nullopt) { 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; m_mv_mat = m_v_mat * m_m_mat;
glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_mv_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));
@@ -174,7 +178,6 @@ void Renderer::render_outline() {
glLineWidth(4.0f); glLineWidth(4.0f);
glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0); glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);
} }
} }
void Renderer::render_sky() { void Renderer::render_sky() {
@@ -185,7 +188,8 @@ void Renderer::render_sky() {
m_mv_loc = shader.loc("mv_matrix"); m_mv_loc = shader.loc("mv_matrix");
m_proj_loc = shader.loc("proj_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_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;
@@ -200,7 +204,6 @@ void Renderer::render_sky() {
glDrawArrays(GL_TRIANGLES, 0, 36); glDrawArrays(GL_TRIANGLES, 0, 36);
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
} }
void Renderer::render_text() { void Renderer::render_text() {
@@ -234,8 +237,10 @@ void Renderer::render_ui() {
glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)0); 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(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, layer)); (void*)offsetof(Vertex2D, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void*)offsetof(Vertex2D, layer));
glEnableVertexAttribArray(0); glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1); glEnableVertexAttribArray(1);
@@ -249,7 +254,6 @@ void Renderer::render_ui() {
glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
} }
void Renderer::update_fov(float fov) { void Renderer::update_fov(float fov) {
@@ -262,9 +266,10 @@ void Renderer::update_proj_matrix(float aspect, float width, float height) {
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); m_ui_proj = glm::ortho(0.0f, width, height, 0.0f, -1.0f, 1.0f);
// scale and then translate // scale and then translate
m_ui_m_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(width / 2.0f, height / 2.0f, 0.0)) * 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)); glm::scale(glm::mat4(1.0f), glm::vec3(50.0f, 50.0f, 1.0f));
} }
void Renderer::render_world() { void Renderer::render_world() {
@@ -291,4 +296,4 @@ void Renderer::render_dev_panel() {
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
} }
} } // namespace Cubed

View File

@@ -1,27 +1,24 @@
#include <Cubed/shader.hpp> #include "Cubed/shader.hpp"
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_hash.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <Cubed/tools/log.hpp> #include "Cubed/tools/cubed_hash.hpp"
#include <Cubed/tools/shader_tools.hpp> #include "Cubed/tools/log.hpp"
#include "Cubed/tools/shader_tools.hpp"
namespace Cubed { 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_program = Tools::create_shader_program(v_shader_path, f_shader_path);
m_name = name; m_name = name;
m_hash = HASH::str(name); m_hash = HASH::str(name);
} }
Shader::Shader(Shader&& shader) noexcept: Shader::Shader(Shader&& shader) noexcept
m_program(shader.m_program), : m_program(shader.m_program), m_hash(shader.m_hash),
m_hash(shader.m_hash), m_name(std::move(shader.m_name)) {
m_name(std::move(shader.m_name))
{
shader.m_hash = 0; shader.m_hash = 0;
shader.m_program = 0; shader.m_program = 0;
} }
@@ -41,7 +38,8 @@ Shader& Shader::operator=(Shader&& shader) noexcept{
return *this; 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) { if (!m_program) {
Logger::warn("Shader has already created !"); Logger::warn("Shader has already created !");
return; return;
@@ -72,7 +70,6 @@ GLuint Shader::loc(const std::string& loc) const {
const std::string& Shader::name() const { const std::string& Shader::name() const {
if (m_name == "-1") { if (m_name == "-1") {
Logger::warn("Shader has already created !"); Logger::warn("Shader has already created !");
} }
return m_name; return m_name;
} }
@@ -82,4 +79,4 @@ void Shader::use() const{
glUseProgram(m_program); glUseProgram(m_program);
} }
} } // namespace Cubed

View File

@@ -1,19 +1,17 @@
#include <Cubed/texture_manager.hpp> #include "Cubed/texture_manager.hpp"
#include <Cubed/constants.hpp>
#include <Cubed/map_table.hpp> #include "Cubed/config.hpp"
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/constants.hpp"
#include <Cubed/tools/log.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 { namespace Cubed {
TextureManager::TextureManager() {}
TextureManager::TextureManager() { TextureManager::~TextureManager() { delet_texture(); }
}
TextureManager::~TextureManager() {
delet_texture();
}
void TextureManager::delet_texture() { void TextureManager::delet_texture() {
glDeleteTextures(1, &m_texture_array); glDeleteTextures(1, &m_texture_array);
@@ -25,13 +23,9 @@ GLuint TextureManager::get_block_status_array() const{
return m_block_status_array; return m_block_status_array;
} }
GLuint TextureManager::get_texture_array() const{ GLuint TextureManager::get_texture_array() const { return m_texture_array; }
return m_texture_array;
}
GLuint TextureManager::get_ui_array() const{ GLuint TextureManager::get_ui_array() const { return m_ui_array; }
return m_ui_array;
}
void TextureManager::load_block_status(unsigned id) { void TextureManager::load_block_status(unsigned id) {
@@ -40,12 +34,8 @@ void TextureManager::load_block_status(unsigned id) {
unsigned char* image_data = nullptr; unsigned char* image_data = nullptr;
image_data = (Tools::load_image_data(path)); image_data = (Tools::load_image_data(path));
glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array); glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id, 16, 16, 1, GL_RGBA,
0 ,0, id, GL_UNSIGNED_BYTE, image_data);
16, 16, 1,
GL_RGBA, GL_UNSIGNED_BYTE,
image_data
);
Tools::delete_image_data(image_data); Tools::delete_image_data(image_data);
} }
@@ -69,16 +59,11 @@ void TextureManager::load_block_texture(unsigned id) {
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array); glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array);
Tools::check_opengl_error(); Tools::check_opengl_error();
for (int i = 0; i < 6; i++) { for (int i = 0; i < 6; i++) {
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id * 6 + i, 16, 16, 1,
0, 0, id * 6 + i, GL_RGBA, GL_UNSIGNED_BYTE, image_data[i]);
16, 16, 1,
GL_RGBA, GL_UNSIGNED_BYTE,
image_data[i]
);
Tools::check_opengl_error(); Tools::check_opengl_error();
Tools::delete_image_data(image_data[i]); Tools::delete_image_data(image_data[i]);
} }
} }
void TextureManager::load_ui_texture(unsigned id) { void TextureManager::load_ui_texture(unsigned id) {
@@ -88,20 +73,16 @@ void TextureManager::load_ui_texture(unsigned id) {
unsigned char* image_data = nullptr; unsigned char* image_data = nullptr;
image_data = (Tools::load_image_data(path)); image_data = (Tools::load_image_data(path));
glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array); glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id, 16, 16, 1, GL_RGBA,
0 ,0, id, GL_UNSIGNED_BYTE, image_data);
16, 16, 1,
GL_RGBA, GL_UNSIGNED_BYTE,
image_data
);
Tools::delete_image_data(image_data); Tools::delete_image_data(image_data);
} }
void TextureManager::init_texture() { void TextureManager::init_texture() {
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &m_max_aniso); glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &m_max_aniso);
if (m_max_aniso > 0.0f) { 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<int>("texture.aniso"); m_aniso = Config::get().get<int>("texture.aniso");
m_aniso = std::min(static_cast<int>(m_max_aniso), m_aniso); m_aniso = std::min(static_cast<int>(m_max_aniso), m_aniso);
@@ -112,12 +93,8 @@ void TextureManager::init_texture() {
Tools::check_opengl_error(); Tools::check_opengl_error();
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array); glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array);
Tools::check_opengl_error(); Tools::check_opengl_error();
glTexImage3D(GL_TEXTURE_2D_ARRAY, glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_BLOCK_NUM * 6, 0,
0, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
16, 16,
MAX_BLOCK_NUM * 6,
0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
Tools::check_opengl_error(); Tools::check_opengl_error();
for (int i = 0; i < MAX_BLOCK_NUM; i++) { for (int i = 0; i < MAX_BLOCK_NUM; i++) {
load_block_texture(i); load_block_texture(i);
@@ -127,24 +104,22 @@ void TextureManager::init_texture() {
Tools::check_opengl_error(); Tools::check_opengl_error();
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
Tools::check_opengl_error(); 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(); Tools::check_opengl_error();
glGenerateMipmap(GL_TEXTURE_2D_ARRAY); glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
Tools::check_opengl_error(); Tools::check_opengl_error();
if (m_aniso >= 1) { if (m_aniso >= 1) {
glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, static_cast<GLfloat>(m_aniso)); glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY,
static_cast<GLfloat>(m_aniso));
} }
glGenTextures(1, &m_block_status_array); glGenTextures(1, &m_block_status_array);
Tools::check_opengl_error(); Tools::check_opengl_error();
glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array); glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array);
Tools::check_opengl_error(); Tools::check_opengl_error();
glTexImage3D(GL_TEXTURE_2D_ARRAY, glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_BLOCK_STATUS, 0,
0, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
16, 16,
MAX_BLOCK_STATUS,
0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
Tools::check_opengl_error(); Tools::check_opengl_error();
for (int i = 0; i < MAX_BLOCK_STATUS; i++) { for (int i = 0; i < MAX_BLOCK_STATUS; i++) {
load_block_status(i); load_block_status(i);
@@ -154,25 +129,23 @@ void TextureManager::init_texture() {
Tools::check_opengl_error(); Tools::check_opengl_error();
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
Tools::check_opengl_error(); 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(); Tools::check_opengl_error();
glGenerateMipmap(GL_TEXTURE_2D_ARRAY); glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
Tools::check_opengl_error(); Tools::check_opengl_error();
if (m_aniso >= 1) { if (m_aniso >= 1) {
glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, static_cast<GLfloat>(m_aniso)); glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY,
static_cast<GLfloat>(m_aniso));
} }
glGenTextures(1, &m_ui_array); glGenTextures(1, &m_ui_array);
Tools::check_opengl_error(); Tools::check_opengl_error();
glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array); glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array);
Tools::check_opengl_error(); Tools::check_opengl_error();
glTexImage3D(GL_TEXTURE_2D_ARRAY, glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_UI_NUM, 0,
0, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
16, 16,
MAX_UI_NUM,
0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
Tools::check_opengl_error(); Tools::check_opengl_error();
for (int i = 0; i < MAX_UI_NUM; i++) { for (int i = 0; i < MAX_UI_NUM; i++) {
load_ui_texture(i); load_ui_texture(i);
@@ -181,8 +154,6 @@ void TextureManager::init_texture() {
glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array); 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_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() { void TextureManager::update() {
@@ -191,9 +162,7 @@ void TextureManager::update() {
} }
} }
void TextureManager::need_reload() { void TextureManager::need_reload() { m_need_reload = true; }
m_need_reload = true;
}
void TextureManager::hot_reload() { void TextureManager::hot_reload() {
delet_texture(); delet_texture();
@@ -202,8 +171,6 @@ void TextureManager::hot_reload() {
m_need_reload = false; m_need_reload = false;
} }
int TextureManager::max_aniso() const { int TextureManager::max_aniso() const { return static_cast<int>(m_max_aniso); }
return static_cast<int>(m_max_aniso);
}
} } // namespace Cubed

View File

@@ -1,30 +1,23 @@
#include <Cubed/tools/cubed_random.hpp> #include "Cubed/tools/cubed_random.hpp"
#include <Cubed/tools/log.hpp>
#include "Cubed/tools/log.hpp"
namespace Cubed { namespace Cubed {
Random::Random() { Random::Random() {}
}
bool Random::random_bool(double probability) { bool Random::random_bool(double probability) {
std::bernoulli_distribution dist(probability); std::bernoulli_distribution dist(probability);
return dist(m_engine); return dist(m_engine);
} }
std::mt19937& Random::engine() { std::mt19937& Random::engine() { return m_engine; }
return m_engine;
}
unsigned Random::seed() { unsigned Random::seed() { return m_seed; }
return m_seed;
}
void Random::init(unsigned seed) { void Random::init(unsigned seed) {
m_seed = seed; m_seed = seed;
m_engine.seed(seed); m_engine.seed(seed);
} }
} } // namespace Cubed

View File

@@ -1,14 +1,14 @@
#include <Cubed/tools/font.hpp> #include "Cubed/tools/font.hpp"
#include <Cubed/constants.hpp>
#include <Cubed/shader.hpp> #include "Cubed/constants.hpp"
#include <Cubed/tools/log.hpp> #include "Cubed/shader.hpp"
#include <Cubed/tools/shader_tools.hpp> #include "Cubed/tools/log.hpp"
#include "Cubed/tools/shader_tools.hpp"
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Cubed { namespace Cubed {
Font::Font() { Font::Font() {
if (FT_Init_FreeType(&m_ft)) { if (FT_Init_FreeType(&m_ft)) {
@@ -37,27 +37,17 @@ void Font::load_character(char8_t c) {
const auto& width = m_face->glyph->bitmap.width; const auto& width = m_face->glyph->bitmap.width;
const auto& height = m_face->glyph->bitmap.rows; const auto& height = m_face->glyph->bitmap.rows;
glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture); glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture);
glTexSubImage3D( glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, static_cast<int>(c), width,
GL_TEXTURE_2D_ARRAY, height, 1, GL_RED, GL_UNSIGNED_BYTE,
0, m_face->glyph->bitmap.buffer);
0,
0,
static_cast<int>(c),
width,
height,
1,
GL_RED,
GL_UNSIGNED_BYTE,
m_face->glyph->bitmap.buffer
);
Character character = { Character character = {
glm::vec2{0.0f, 0.0f}, glm::vec2{0.0f, 0.0f},
glm::vec2{static_cast<float>(width) / m_texture_width, static_cast<float>(height) / m_texture_height}, glm::vec2{static_cast<float>(width) / m_texture_width,
static_cast<float>(height) / m_texture_height},
glm::ivec2(m_face->glyph->bitmap.width, m_face->glyph->bitmap.rows), glm::ivec2(m_face->glyph->bitmap.width, m_face->glyph->bitmap.rows),
glm::ivec2(m_face->glyph->bitmap_left, m_face->glyph->bitmap_top), glm::ivec2(m_face->glyph->bitmap_left, m_face->glyph->bitmap_top),
static_cast<GLuint>(m_face->glyph->advance.x) static_cast<GLuint>(m_face->glyph->advance.x)};
};
m_characters.insert({c, std::move(character)}); m_characters.insert({c, std::move(character)});
} }
@@ -67,18 +57,9 @@ void Font::setup_font_character() {
glGenTextures(1, &m_text_texture); glGenTextures(1, &m_text_texture);
glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture); glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture);
glTexImage3D( glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RED, m_texture_width,
GL_TEXTURE_2D_ARRAY, m_texture_height, MAX_CHARACTER, 0, GL_RED, GL_UNSIGNED_BYTE,
0, nullptr);
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++) { for (char8_t c = 0; c < 128; c++) {
load_character(c); load_character(c);
@@ -91,7 +72,8 @@ void Font::setup_font_character() {
glBindTexture(GL_TEXTURE_2D_ARRAY, 0); glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
} }
std::vector<Vertex2D> Font::vertices(const std::string &text, float x, float y, float scale) { std::vector<Vertex2D> Font::vertices(const std::string& text, float x, float y,
float scale) {
static Font font; static Font font;
std::vector<Vertex2D> vertices; std::vector<Vertex2D> vertices;
@@ -109,26 +91,27 @@ std::vector<Vertex2D> Font::vertices(const std::string &text, float x, float y,
float w = ch.size.x * scale; float w = ch.size.x * scale;
float h = ch.size.y * scale; float h = ch.size.y * scale;
vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, static_cast<float>(c)); vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y,
vertices.emplace_back(xpos, ypos, ch.uv_min.x, ch.uv_min.y, static_cast<float>(c)); static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, static_cast<float>(c)); vertices.emplace_back(xpos, ypos, ch.uv_min.x, ch.uv_min.y,
vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, static_cast<float>(c)); static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, static_cast<float>(c)); vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y,
vertices.emplace_back(xpos + w, ypos + h, ch.uv_max.x, ch.uv_max.y, static_cast<float>(c)); static_cast<float>(c));
vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y,
static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y,
static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos + h, ch.uv_max.x, ch.uv_max.y,
static_cast<float>(c));
x += (ch.advance >> 6) * scale; x += (ch.advance >> 6) * scale;
} }
return vertices; return vertices;
} }
GLuint Font::text_texture() { GLuint Font::text_texture() { return m_text_texture; }
return m_text_texture;
}
const std::string& Font::font_path() { const std::string& Font::font_path() { return m_font_path; }
return m_font_path;
}
} } // namespace Cubed

View File

@@ -1,12 +1,12 @@
#include <Cubed/tools/math_tools.hpp> #include "Cubed/tools/math_tools.hpp"
#include <glm/gtc/type_ptr.hpp> #include <glm/gtc/type_ptr.hpp>
namespace Cubed { namespace Cubed {
namespace Math { namespace Math {
void extract_frustum_planes(const glm::mat4& mvp_matrix, std::vector<glm::vec4>& planes) { void extract_frustum_planes(const glm::mat4& mvp_matrix,
std::vector<glm::vec4>& planes) {
if (planes.size() != 6) { if (planes.size() != 6) {
planes.resize(6); planes.resize(6);
} }
@@ -14,25 +14,29 @@ namespace Math {
const float* m = glm::value_ptr(mvp_matrix); const float* m = glm::value_ptr(mvp_matrix);
// left plane // left plane
planes[0] = glm::vec4(m[3] + m[0], m[7] + m[4], m[11] + m[8], m[15] + m[12]); planes[0] =
glm::vec4(m[3] + m[0], m[7] + m[4], m[11] + m[8], m[15] + m[12]);
// right plane // right plane
planes[1] = glm::vec4(m[3] - m[0], m[7] - m[4], m[11] - m[8], m[15] - m[12]); planes[1] =
glm::vec4(m[3] - m[0], m[7] - m[4], m[11] - m[8], m[15] - m[12]);
// bottom plane // bottom plane
planes[2] = glm::vec4(m[3] + m[1], m[7] + m[5], m[11] + m[9], m[15] + m[13]); planes[2] =
glm::vec4(m[3] + m[1], m[7] + m[5], m[11] + m[9], m[15] + m[13]);
// top plane // top plane
planes[3] = glm::vec4(m[3] - m[1], m[7] - m[5], m[11] - m[9], m[15] - m[13]); planes[3] =
glm::vec4(m[3] - m[1], m[7] - m[5], m[11] - m[9], m[15] - m[13]);
// near plane // near plane
planes[4] = glm::vec4(m[3] + m[2], m[7] + m[6], m[11] + m[10], m[15] + m[14]); planes[4] =
glm::vec4(m[3] + m[2], m[7] + m[6], m[11] + m[10], m[15] + m[14]);
// far plane // far plane
planes[5] = glm::vec4(m[3] - m[2], m[7] - m[6], m[11] - m[10], m[15] - m[14]); planes[5] =
glm::vec4(m[3] - m[2], m[7] - m[6], m[11] - m[10], m[15] - m[14]);
for (auto& p : planes) { for (auto& p : planes) {
p = glm::normalize(p); p = glm::normalize(p);
} }
} }
} // namespace Math
} } // namespace Cubed
}

View File

@@ -1,15 +1,15 @@
#include <Cubed/tools/perlin_noise.hpp> #include "Cubed/tools/perlin_noise.hpp"
#include "Cubed/config.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_random.hpp"
#include <Cubed/config.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_random.hpp>
#include <algorithm> #include <algorithm>
#include <numeric> #include <numeric>
#include <random> #include <random>
namespace Cubed { namespace Cubed {
void PerlinNoise::init(unsigned seed) { void PerlinNoise::init(unsigned seed) {
p.resize(256); p.resize(256);
std::iota(p.begin(), p.end(), 0); 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 ba = p[b] + iz;
int bb = p[b + 1] + iz; int bb = p[b + 1] + iz;
float res = lerp (w, 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(v,
lerp(u, grad(p[aa], x, y, z), grad(p[ba], x - 1, y, z)), lerp(u, grad(p[aa + 1], x, y, z - 1),
lerp(u, grad(p[ab], x, y - 1, z), grad(p[bb], x - 1, y - 1, z)) grad(p[ba + 1], x - 1, y, z - 1)),
), lerp(u, grad(p[ab + 1], x, y - 1, z - 1),
lerp(v, 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; return (res + 1.0f) / 2.0f;
} }
float PerlinNoise::fade(float t) { float PerlinNoise::fade(float t) { return t * t * t * (t * (t * 6 - 15) + 10); }
return t * t * t * (t * (t * 6 - 15) + 10);
}
float PerlinNoise::lerp(float t, float a, float b) { float PerlinNoise::lerp(float t, float a, float b) { return a + t * (b - a); }
return a + t * (b - a);
}
float PerlinNoise::grad(int hash, float x, float y, float z) { float PerlinNoise::grad(int hash, float x, float y, float z) {
int h = hash & 15; int h = hash & 15;
@@ -83,4 +79,4 @@ void PerlinNoise::reload(unsigned seed) {
is_init = true; is_init = true;
} }
} } // namespace Cubed

View File

@@ -1,22 +1,25 @@
#include <fstream> #include "Cubed/tools/shader_tools.hpp"
#include <filesystem>
#include <Cubed/config.hpp> #include "Cubed/config.hpp"
#include <Cubed/tools/cubed_assert.hpp> #include "Cubed/tools/cubed_assert.hpp"
#include <Cubed/tools/shader_tools.hpp> #include "Cubed/tools/log.hpp"
#include <Cubed/tools/log.hpp>
#include <filesystem>
#include <fstream>
namespace Cubed { namespace Cubed {
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Tools { 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 v_shader_str =
std::string f_shader_str = Tools::read_shader_source(ASSETS_PATH + f_shader_path); 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* v_shader_source = v_shader_str.c_str();
const char* f_shader_source = f_shader_str.c_str(); const char* f_shader_source = f_shader_str.c_str();
@@ -60,7 +63,6 @@ namespace Tools {
return vf_program; return vf_program;
} }
void print_shader_log(GLuint shader) { void print_shader_log(GLuint shader) {
int len = 0; int len = 0;
int ch_written = 0; int ch_written = 0;
@@ -72,10 +74,8 @@ namespace Tools {
Logger::info("Shader Info Log: {}", log); Logger::info("Shader Info Log: {}", log);
free(log); free(log);
} }
} }
void print_program_info(int prog) { void print_program_info(int prog) {
int len = 0; int len = 0;
int ch_written = 0; int ch_written = 0;
@@ -101,7 +101,6 @@ namespace Tools {
return found_error; return found_error;
} }
std::string read_shader_source(const std::string& file_path) { std::string read_shader_source(const std::string& file_path) {
std::string content; std::string content;
std::ifstream file_stream(file_path, std::ios::in); std::ifstream file_stream(file_path, std::ios::in);
@@ -120,21 +119,20 @@ namespace Tools {
return content; return content;
} }
void delete_image_data(unsigned char* data) { void delete_image_data(unsigned char* data) { SOIL_free_image_data(data); }
SOIL_free_image_data(data);
}
unsigned char* load_image_data(const std::string& tex_image_path) { unsigned char* load_image_data(const std::string& tex_image_path) {
fs::path path = ASSETS_PATH + tex_image_path; fs::path path = ASSETS_PATH + tex_image_path;
ASSERT_MSG(fs::is_regular_file(path), path.c_str()); ASSERT_MSG(fs::is_regular_file(path), path.c_str());
unsigned char* data = nullptr; unsigned char* data = nullptr;
int width, height, channels; int width, height, channels;
data = SOIL_load_image(path.string().c_str(), &width, &height, &channels, SOIL_LOAD_AUTO); data = SOIL_load_image(path.string().c_str(), &width, &height, &channels,
SOIL_LOAD_AUTO);
ASSERT_MSG(data, "Could not load texture" + path.string()); ASSERT_MSG(data, "Could not load texture" + path.string());
return data; return data;
} }
} } // namespace Tools
} } // namespace Cubed

View File

@@ -1,26 +1,19 @@
#include <Cubed/ui/text.hpp> #include "Cubed/ui/text.hpp"
#include <Cubed/shader.hpp> #include "Cubed/shader.hpp"
#include <Cubed/tools/cubed_hash.hpp> #include "Cubed/tools/cubed_hash.hpp"
#include <Cubed/tools/font.hpp> #include "Cubed/tools/font.hpp"
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp> #include <glm/gtc/type_ptr.hpp>
namespace Cubed { namespace Cubed {
Text::Text(std::string_view name) : NAME(name), UUID(HASH::str(name)) {}
Text::Text(std::string_view name) : Text::Text(std::string_view name, std::string_view str, glm::vec2 pos,
NAME(name), Color color)
UUID(HASH::str(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))
{
m_text.assign(str); m_text.assign(str);
m_pos = pos; m_pos = pos;
m_color = color_value(color); m_color = color_value(color);
@@ -33,17 +26,11 @@ Text::~Text() {
} }
} }
Text::Text(Text&& other) noexcept : Text::Text(Text&& other) noexcept
m_scale(other.m_scale), : m_scale(other.m_scale), m_pos(other.m_pos), NAME(other.NAME),
m_pos(other.m_pos), UUID(other.UUID), m_text(std::move(other.m_text)), m_color(other.m_color),
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_model_matrix(other.m_model_matrix),
m_vertices(std::move(other.m_vertices)), m_vertices(std::move(other.m_vertices)), m_vbo(other.m_vbo) {
m_vbo(other.m_vbo)
{
other.m_vbo = 0; other.m_vbo = 0;
} }
@@ -62,9 +49,7 @@ Text& Text::scale(float s) {
return *this; return *this;
} }
std::size_t Text::uuid() const { std::size_t Text::uuid() const { return UUID; }
return UUID;
}
void Text::set_loc(const Shader& shader) { void Text::set_loc(const Shader& shader) {
m_color_loc = shader.loc("textColor"); m_color_loc = shader.loc("textColor");
@@ -84,7 +69,8 @@ void Text::render() {
glBindTexture(GL_TEXTURE_2D_ARRAY, Font::text_texture()); glBindTexture(GL_TEXTURE_2D_ARRAY, Font::text_texture());
ASSERT_MSG(m_color_loc, "m_color_loc is null"); 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)) * 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)); 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); glUniform3f(m_color_loc, m_color.x, m_color.y, m_color.z);
@@ -92,8 +78,10 @@ void Text::render() {
glBindBuffer(GL_ARRAY_BUFFER, m_vbo); glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)0); 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(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, layer)); (void*)offsetof(Vertex2D, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void*)offsetof(Vertex2D, layer));
glEnableVertexAttribArray(0); glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1); glEnableVertexAttribArray(1);
@@ -115,11 +103,10 @@ void Text::upload_to_gpu() {
} }
ASSERT_MSG(m_vbo, "Vbo Is Not Gen"); ASSERT_MSG(m_vbo, "Vbo Is Not Gen");
glBindBuffer(GL_ARRAY_BUFFER, m_vbo); 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 { bool Text::operator==(const Text& other) const { return UUID == other.uuid(); }
return UUID == other.uuid();
}
} } // namespace Cubed

View File

@@ -1,10 +1,10 @@
#include <Cubed/renderer.hpp> #include "Cubed/window.hpp"
#include <Cubed/input.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/window.hpp>
#include <Cubed/tools/font.hpp> #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 <imgui.h> #include <imgui.h>
#include <imgui_impl_glfw.h> #include <imgui_impl_glfw.h>
@@ -15,11 +15,7 @@ namespace Cubed {
static int windowed_xpos = 0, windowed_ypos = 0; static int windowed_xpos = 0, windowed_ypos = 0;
static int windowed_width = 800, windowed_height = 600; static int windowed_width = 800, windowed_height = 600;
Window::Window(Renderer& renderer) : Window::Window(Renderer& renderer) : m_renderer(renderer) {}
m_renderer(renderer)
{
}
Window::~Window() { Window::~Window() {
@@ -35,17 +31,11 @@ Window::~Window() {
glfwTerminate(); glfwTerminate();
} }
bool Window::is_mouse_enable() const { bool Window::is_mouse_enable() const { return m_mouse_enable; }
return m_mouse_enable;
}
const GLFWwindow* Window::get_glfw_window() const { const GLFWwindow* Window::get_glfw_window() const { return m_window; }
return m_window;
}
GLFWwindow* Window::get_glfw_window() { GLFWwindow* Window::get_glfw_window() { return m_window; }
return m_window;
}
void Window::update_viewport() { void Window::update_viewport() {
glfwGetFramebufferSize(m_window, &m_width, &m_height); glfwGetFramebufferSize(m_window, &m_width, &m_height);
@@ -56,7 +46,6 @@ void Window::update_viewport() {
config.set("window.width", windowed_width); config.set("window.width", windowed_width);
config.set("window.height", windowed_height); config.set("window.height", windowed_height);
} }
void Window::init() { void Window::init() {
@@ -74,7 +63,8 @@ void Window::init() {
if (config.get<bool>("window.fullscreen")) { if (config.get<bool>("window.fullscreen")) {
GLFWmonitor* primary_monitor = glfwGetPrimaryMonitor(); GLFWmonitor* primary_monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary_monitor); 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 { } else {
m_window = glfwCreateWindow(m_width, m_height, "Cubed", NULL, NULL); m_window = glfwCreateWindow(m_width, m_height, "Cubed", NULL, NULL);
} }
@@ -86,7 +76,6 @@ void Window::init() {
glfwSwapInterval(0); glfwSwapInterval(0);
} }
glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (glfwRawMouseMotionSupported()) { if (glfwRawMouseMotionSupported()) {
glfwSetInputMode(m_window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE); glfwSetInputMode(m_window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
@@ -96,8 +85,8 @@ void Window::init() {
GLFWmonitor* primary = glfwGetPrimaryMonitor(); GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary); const GLFWvidmode* mode = glfwGetVideoMode(primary);
glfwSetWindowPos(m_window, static_cast<int>(mode->width / 2.0f) - 400, static_cast<int>(mode->height / 2.0f) - 300); glfwSetWindowPos(m_window, static_cast<int>(mode->width / 2.0f) - 400,
static_cast<int>(mode->height / 2.0f) - 300);
} }
void Window::hot_reload() { void Window::hot_reload() {
@@ -119,27 +108,14 @@ void Window::hot_reload() {
GLFWmonitor* primary = glfwGetPrimaryMonitor(); GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary); const GLFWvidmode* mode = glfwGetVideoMode(primary);
glfwSetWindowMonitor( glfwSetWindowMonitor(m_window, primary, 0, 0, mode->width, mode->height,
m_window, GL_DONT_CARE);
primary,
0,
0,
mode->width,
mode->height,
GL_DONT_CARE
);
} else { } else {
GLFWmonitor* monitor = glfwGetWindowMonitor(m_window); GLFWmonitor* monitor = glfwGetWindowMonitor(m_window);
if (monitor != nullptr) { if (monitor != nullptr) {
glfwSetWindowMonitor( glfwSetWindowMonitor(m_window, nullptr, windowed_xpos,
m_window, windowed_ypos, windowed_width, windowed_height,
nullptr, 0);
windowed_xpos,
windowed_ypos,
windowed_width,
windowed_height,
0
);
} else { } else {
Logger::error("Can't Find Monitor"); Logger::error("Can't Find Monitor");
} }
@@ -157,15 +133,8 @@ void Window::toggle_fullscreen() {
auto& config = Config::get(); auto& config = Config::get();
GLFWmonitor* monitor = glfwGetWindowMonitor(m_window); GLFWmonitor* monitor = glfwGetWindowMonitor(m_window);
if (monitor != nullptr) { if (monitor != nullptr) {
glfwSetWindowMonitor( glfwSetWindowMonitor(m_window, nullptr, windowed_xpos, windowed_ypos,
m_window, windowed_width, windowed_height, 0);
nullptr,
windowed_xpos,
windowed_ypos,
windowed_width,
windowed_height,
0
);
config.set("window.fullscreen", false); config.set("window.fullscreen", false);
} else { } else {
@@ -175,17 +144,9 @@ void Window::toggle_fullscreen() {
GLFWmonitor* primary = glfwGetPrimaryMonitor(); GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary); const GLFWvidmode* mode = glfwGetVideoMode(primary);
glfwSetWindowMonitor( glfwSetWindowMonitor(m_window, primary, 0, 0, mode->width, mode->height,
m_window, GL_DONT_CARE);
primary,
0,
0,
mode->width,
mode->height,
GL_DONT_CARE
);
config.set("window.fullscreen", true); config.set("window.fullscreen", true);
} }
update_viewport(); update_viewport();
} }
@@ -210,16 +171,25 @@ void Window::toggle_mouse_able() {
void Window::imgui_init() { void Window::imgui_init() {
float dpi_scale_x, dpi_scale_y; float dpi_scale_x, dpi_scale_y;
glfwGetWindowContentScale(m_window, &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; float main_scale = dpi_scale_x;
Logger::info("Main Scale {}", main_scale); Logger::info("Main Scale {}", main_scale);
// Setup Dear ImGui context // Setup Dear ImGui context
IMGUI_CHECKVERSION(); IMGUI_CHECKVERSION();
ImGui::CreateContext(); ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.ConfigFlags |=
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard 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_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<int>("devpanel.theme"); auto theme = Config::get().get<int>("devpanel.theme");
if (theme == 0) { if (theme == 0) {
ImGui::StyleColorsDark(); ImGui::StyleColorsDark();
@@ -231,7 +201,10 @@ void Window::imgui_init() {
} }
ImGuiStyle& style = ImGui::GetStyle(); 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.FontScaleDpi = main_scale;
style.FontSizeBase = 20.0f; style.FontSizeBase = 20.0f;
ImFont* font = io.Fonts->AddFontFromFileTTF(Font::font_path().c_str()); ImFont* font = io.Fonts->AddFontFromFileTTF(Font::font_path().c_str());
@@ -241,4 +214,4 @@ void Window::imgui_init() {
ImGui_ImplOpenGL3_Init(); ImGui_ImplOpenGL3_Init();
} }
} } // namespace Cubed

2
third_party/.clang-format vendored Normal file
View File

@@ -0,0 +1,2 @@
DisableFormat: true
SortIncludes: false