diff --git a/.clang-format b/.clang-format index 2eee897..543285d 100644 --- a/.clang-format +++ b/.clang-format @@ -1,58 +1,99 @@ --- -Language: Cpp BasedOnStyle: WebKit -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: "true" -AlignConsecutiveDeclarations: "false" +AccessModifierOffset: -4 +AlignAfterOpenBracket: BlockIndent +AlignArrayOfStructures: Left +AlignConsecutiveAssignments: Consecutive +AlignConsecutiveBitFields: Consecutive +AlignConsecutiveDeclarations: None +AlignConsecutiveMacros: Consecutive AlignEscapedNewlines: Right -AlignOperands: "true" -AlignTrailingComments: "true" -AllowShortBlocksOnASingleLine: "true" -AllowShortCaseLabelsOnASingleLine: "true" +AlignOperands: AlignAfterOperator +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: true +AllowShortEnumsOnASingleLine: false AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: "true" -AllowShortLoopsOnASingleLine: "true" -AlwaysBreakAfterDefinitionReturnType: None +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: true AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: "false" -AlwaysBreakTemplateDeclarations: "true" -BinPackArguments: "true" -BinPackParameters: "true" -BreakBeforeBraces: Allman -BreakBeforeInheritanceComma: "true" -BreakBeforeTernaryOperators: "true" +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: false +BinPackParameters: false +BitFieldColonSpacing: After +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Never + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: All +BreakBeforeBraces: Custom +BreakBeforeConceptDeclarations: true +BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeComma -BreakStringLiterals: "true" -ColumnLimit: "120" -CompactNamespaces: "false" -ConstructorInitializerAllOnOneLineOrOnePerLine: "true" -Cpp11BracedListStyle: "true" -DisableFormat: "false" -FixNamespaceComments: "true" -IndentCaseLabels: "true" -IndentWrappedFunctionNames: "false" -KeepEmptyLinesAtTheStartOfBlocks: "true" -MaxEmptyLinesToKeep: "1" +BreakInheritanceList: BeforeComma +BreakStringLiterals: true +ColumnLimit: 92 +CompactNamespaces: false +Cpp11BracedListStyle: true +DisableFormat: false +FixNamespaceComments: true +IndentCaseLabels: true +IndentPPDirectives: BeforeHash +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +KeepEmptyLinesAtTheStartOfBlocks: true +Language: Cpp +LambdaBodyIndentation: OuterScope +MaxEmptyLinesToKeep: 1 NamespaceIndentation: None +PackConstructorInitializers: CurrentLine PointerAlignment: Left -ReflowComments: "true" -SortIncludes: "true" -SortUsingDeclarations: "true" -SpaceAfterTemplateKeyword: "false" -SpaceBeforeAssignmentOperators: "true" +ReferenceAlignment: Left +ReflowComments: true +SeparateDefinitionBlocks: Always +SortIncludes: CaseInsensitive +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements -SpaceInEmptyParentheses: "false" -SpacesBeforeTrailingComments: "2" -SpacesInAngles: "false" -SpacesInCStyleCastParentheses: "false" -SpacesInContainerLiterals: "false" -SpacesInParentheses: "false" -SpacesInSquareBrackets: "false" -Standard: Cpp11 +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesInAngles: false +SpacesBeforeTrailingComments: 2 +SpacesInCStyleCastParentheses: false +SpacesInContainerLiterals: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: 1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto UseTab: Never ---- -Language: Proto ---- -Language: ObjC -BasedOnStyle: WebKit -ColumnLimit: "120" +QualifierAlignment: Custom +QualifierOrder: ["inline", "static", "constexpr", "type", "const", "volatile"] diff --git a/.clang-tidy b/.clang-tidy index 8c141c7..a297d2e 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,11 +1,14 @@ Checks: > *-, + boost-*, bugprone-*, -bugprone-macro-parentheses, + cert-*, + -cert-err58-cpp, -cert-oop54-cpp, clang-analyzer-*, @@ -15,39 +18,35 @@ Checks: > cppcoreguidelines-*, -cppcoreguidelines-avoid-magic-numbers, - -cppcoreguidelines-macro-usage, - -cppcoreguidelines-special-member-functions, + -cppcoreguidelines-avoid-const-or-ref-data-members, + -cppcoreguidelines-pro-bounds-constant-array-index, -cppcoreguidelines-pro-bounds-pointer-arithmetic, - -cppcoreguidelines-pro-bounds-array-to-pointer-decay, hicpp-*, - -hicpp-special-member-functions, - -hicpp-no-array-decay, - -hicpp-signed-bitwise, misc-*, modernize-*, - -modernize-avoid-bind, - -modernize-use-trailing-return-type, performance-*, readability-*, + -readability-identifier-naming, -readability-const-return-type, -readability-identifier-length, -readability-magic-numbers, - readability-identifier-naming, - -readability-uppercase-literal-suffix, - -*non-private-member-variables-in-classes, - -*-avoid-c-arrays + -*-named-parameter, + -*-non-private-member-variables-in-classes, + -*-special-member-functions, WarningsAsErrors: "*" FormatStyle: none CheckOptions: - key: bugprone-easily-swappable-parameters.MinimumLength value: 4 + - key: cppcoreguidelines-avoid-do-while.IgnoreMacros + value: true - key: readability-identifier-naming.ClassCase value: CamelCase - key: readability-identifier-naming.ClassMemberCase @@ -60,6 +59,8 @@ CheckOptions: value: CamelCase - key: readability-identifier-naming.FunctionCase value: camelBack + - key: readability-identifier-naming.FunctionIgnoredRegexp + value: "^tag_invoke$" - key: readability-identifier-naming.GlobalConstantCase value: CamelCase - key: readability-identifier-naming.IgnoreMainLikeFunctions diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index eb64181..5d189bc 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,7 +15,7 @@ repos: - id: check-case-conflict - id: check-added-large-files - # - repo: https://github.com/pre-commit/mirrors-clang-format - # rev: v17.0.2 - # hooks: - # - id: clang-format + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: v17.0.2 + hooks: + - id: clang-format diff --git a/src/app/playground/cxx_stb_image/main.cpp b/src/app/playground/cxx_stb_image/main.cpp index 8f03417..f2531da 100644 --- a/src/app/playground/cxx_stb_image/main.cpp +++ b/src/app/playground/cxx_stb_image/main.cpp @@ -17,7 +17,9 @@ int main(int, char**) stbi_set_flip_vertically_on_load(1); buffer = stbi_load(path, &width, &height, &bpp, 0); - if (buffer == nullptr) { MOCI_ERROR("stbi load error"); } + if (buffer == nullptr) { + MOCI_ERROR("stbi load error"); + } MOCI_INFO("Width: {}", width); MOCI_INFO("Height: {}", height); @@ -25,22 +27,34 @@ int main(int, char**) // Resize auto const newSize = 512; - std::vector outBuffer {}; + std::vector outBuffer{}; outBuffer.resize(newSize * newSize * bpp); - if (stbir_resize_uint8(buffer, width, height, 0, outBuffer.data(), newSize, newSize, 0, bpp) == 0) - { + if (stbir_resize_uint8( + buffer, + width, + height, + 0, + outBuffer.data(), + newSize, + newSize, + 0, + bpp + ) + == 0) { MOCI_ERROR("stbi resize error"); } // Write auto const outPath = "test.png"; - if (stbi_write_png(outPath, newSize, newSize, bpp, outBuffer.data(), newSize * bpp) == 0) - { + if (stbi_write_png(outPath, newSize, newSize, bpp, outBuffer.data(), newSize * bpp) + == 0) { MOCI_ERROR("stbi write error"); } // Cleanup - if (buffer != nullptr) { stbi_image_free(buffer); } + if (buffer != nullptr) { + stbi_image_free(buffer); + } return EXIT_SUCCESS; } diff --git a/src/app/playground/freetype_atlas/main.cpp b/src/app/playground/freetype_atlas/main.cpp index e100dee..4df5dfb 100644 --- a/src/app/playground/freetype_atlas/main.cpp +++ b/src/app/playground/freetype_atlas/main.cpp @@ -21,8 +21,7 @@ struct glyph_info int main(int argc, char** argv) { auto const arguments = std::span(argv, argc); - if (argc < 3) - { + if (argc < 3) { printf("usage: %s \n", arguments[0]); return 1; } @@ -36,9 +35,12 @@ int main(int argc, char** argv) // quick and dirty max texture size estimate - int max_dim = (1 + (face->size->metrics.height >> 6)) * static_cast(ceilf(sqrtf(NUM_GLYPHS))); + int max_dim = (1 + (face->size->metrics.height >> 6)) + * static_cast(ceilf(sqrtf(NUM_GLYPHS))); int tex_width = 1; - while (tex_width < max_dim) { tex_width <<= 1; } + while (tex_width < max_dim) { + tex_width <<= 1; + } int tex_height = tex_width; // render glyphs to atlas @@ -47,26 +49,26 @@ int main(int argc, char** argv) int pen_x = 0; int pen_y = 0; - std::array info {}; + std::array info{}; auto index = 0; - for (auto& glyph : info) - { - FT_Load_Char(face, index, FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT | FT_LOAD_TARGET_LIGHT); + for (auto& glyph : info) { + FT_Load_Char( + face, + index, + FT_LOAD_RENDER | FT_LOAD_FORCE_AUTOHINT | FT_LOAD_TARGET_LIGHT + ); index++; FT_Bitmap* bmp = &face->glyph->bitmap; - if (pen_x + static_cast(bmp->width) >= tex_width) - { + if (pen_x + static_cast(bmp->width) >= tex_width) { pen_x = 0; pen_y += ((face->size->metrics.height >> 6) + 1); } - for (int row = 0; row < static_cast(bmp->rows); ++row) - { - for (int col = 0; col < static_cast(bmp->width); ++col) - { + for (int row = 0; row < static_cast(bmp->rows); ++row) { + for (int col = 0; col < static_cast(bmp->width); ++col) { int x = pen_x + col; int y = pen_y + row; pixels[y * tex_width + x] = bmp->buffer[row * bmp->pitch + col]; @@ -92,8 +94,7 @@ int main(int argc, char** argv) // write png char* png_data = (char*)calloc(tex_width * tex_height * 4, 1); - for (int i = 0; i < (tex_width * tex_height); ++i) - { + for (int i = 0; i < (tex_width * tex_height); ++i) { png_data[i * 4 + 0] |= pixels[i]; png_data[i * 4 + 1] |= pixels[i]; png_data[i * 4 + 2] |= pixels[i]; diff --git a/src/app/playground/gl_extensions/main.cpp b/src/app/playground/gl_extensions/main.cpp index bf51587..43522b8 100644 --- a/src/app/playground/gl_extensions/main.cpp +++ b/src/app/playground/gl_extensions/main.cpp @@ -6,8 +6,7 @@ auto main() -> int { - if (auto success = glfwInit(); success == GLFW_FALSE) - { + if (auto success = glfwInit(); success == GLFW_FALSE) { std::fprintf(stderr, "Failed to initialize glfw\n"); return EXIT_FAILURE; } @@ -16,10 +15,13 @@ auto main() -> int glfwHideWindow(window); glfwMakeContextCurrent(window); - if (auto err = glewInit() != GLEW_OK; err) - { + if (auto err = glewInit() != GLEW_OK; err) { auto const* msg = glewGetErrorString(err); - std::fprintf(stderr, "Failed to initialize glew: %s\n", reinterpret_cast(msg)); + std::fprintf( + stderr, + "Failed to initialize glew: %s\n", + reinterpret_cast(msg) + ); return EXIT_FAILURE; } @@ -27,9 +29,8 @@ auto main() -> int glGetIntegerv(GL_NUM_EXTENSIONS, &n); std::printf("num: %d\n", n); - for (GLint i = 0; i < n; i++) - { - const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i); + for (GLint i = 0; i < n; i++) { + char const* extension = (char const*)glGetStringi(GL_EXTENSIONS, i); printf("Ext %d: %s\n", i, extension); } diff --git a/src/app/playground/sdl_emscripten/main.cpp b/src/app/playground/sdl_emscripten/main.cpp index cb36408..1c60544 100644 --- a/src/app/playground/sdl_emscripten/main.cpp +++ b/src/app/playground/sdl_emscripten/main.cpp @@ -25,8 +25,7 @@ static auto mainLoop(void*) -> void; int main(int, char**) { - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) - { + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { std::fprintf(stderr, "Error: %s\n", SDL_GetError()); return -1; } @@ -50,13 +49,18 @@ int main(int, char**) SDL_GetCurrentDisplayMode(0, ¤t); auto flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI; - auto app = Application {}; - app.window - = SDL_CreateWindow("Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, (SDL_WindowFlags)flags); + auto app = Application{}; + app.window = SDL_CreateWindow( + "Title", + SDL_WINDOWPOS_CENTERED, + SDL_WINDOWPOS_CENTERED, + 1280, + 720, + (SDL_WindowFlags)flags + ); app.graphicsContext = SDL_GL_CreateContext(app.window); - if (!app.graphicsContext) - { + if (!app.graphicsContext) { std::fprintf(stderr, "Failed to initialize WebGL context!\n"); return 1; } @@ -83,21 +87,27 @@ static auto mainLoop(void* arg) -> void auto* app = static_cast(arg); auto& color = app->color; - auto event = SDL_Event {}; - while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); } + auto event = SDL_Event{}; + while (SDL_PollEvent(&event)) { + ImGui_ImplSDL2_ProcessEvent(&event); + } ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL2_NewFrame(); ImGui::NewFrame(); - if (app->showDemoWindow) { ImGui::ShowDemoWindow(&app->showDemoWindow); } + if (app->showDemoWindow) { + ImGui::ShowDemoWindow(&app->showDemoWindow); + } ImGui::Begin("Hello, world!"); ImGui::Text("This is some useful text."); ImGui::Checkbox("Demo Window", &app->showDemoWindow); ImGui::ColorEdit3("clear color", (float*)&color); - if (ImGui::Button("Button")) { app->counter++; } + if (ImGui::Button("Button")) { + app->counter++; + } ImGui::SameLine(); ImGui::Text("counter = %d", app->counter); diff --git a/src/app/sandbox2D/main.cpp b/src/app/sandbox2D/main.cpp index 3716081..27d60fc 100644 --- a/src/app/sandbox2D/main.cpp +++ b/src/app/sandbox2D/main.cpp @@ -16,12 +16,16 @@ #include #include -static std::atomic level {0.5F}; +static std::atomic level{0.5F}; class LevelMeterView : public moci::Component { public: - LevelMeterView(moci::ColorRGBA32 col, std::string id) : Component(std::move(id)), _color(col) { } + LevelMeterView(moci::ColorRGBA32 col, std::string id) + : Component(std::move(id)) + , _color(col) + {} + ~LevelMeterView() override = default; auto onDraw(moci::Painter& painter) -> void override @@ -30,22 +34,23 @@ class LevelMeterView : public moci::Component auto area = getBounds(); auto const ledHeight = area.getHeight() / (numLEDs); - for (auto i = 0; i < (numLEDs * level.load()); i++) - { + for (auto i = 0; i < (numLEDs * level.load()); i++) { auto const ledBounds = area.removeFromBottom(ledHeight).reduced(1); painter.drawQuad(ledBounds.toFloat(), _color); } } private: - constexpr static int numLEDs = 100; + static constexpr int numLEDs = 100; - moci::ColorRGBA32 _color {}; + moci::ColorRGBA32 _color{}; }; float linearToDecibel(float linear) { - if (linear != 0.0F) { return 20.0F * log10f(linear); } + if (linear != 0.0F) { + return 20.0F * log10f(linear); + } return -144.0F; // effectively minus infinity } @@ -56,45 +61,42 @@ class MultiChannel : public moci::Component { MOCI_PROFILE_FUNCTION(); _listener.bind("", 8080); - _listener.setMessageCallback( - [](auto const& buffer, auto const size) - { - moci::ignoreUnused(size); - auto data = float {}; - std::memcpy(&data, buffer.data(), sizeof(data)); - level.store((144.0F - std::abs(linearToDecibel(data))) / 144.0F); - - // auto data = Data{}; - // std::memcpy(&data, buffer.data(), sizeof(data)); - // std::printf("Data: %u - %u, %f\n", data.type, data.id, data.value); - }); + _listener.setMessageCallback([](auto const& buffer, auto const size) { + moci::ignoreUnused(size); + auto data = float{}; + std::memcpy(&data, buffer.data(), sizeof(data)); + level.store((144.0F - std::abs(linearToDecibel(data))) / 144.0F); + + // auto data = Data{}; + // std::memcpy(&data, buffer.data(), sizeof(data)); + // std::printf("Data: %u - %u, %f\n", data.type, data.id, data.value); + }); _listener.listen(); - for (auto i = 0; i < 5; i++) - { - auto col = moci::ColorRGBA32 {0.2F * static_cast(i), 0.8F, 0.2F, 1.0F}; + for (auto i = 0; i < 5; i++) { + auto col = moci::ColorRGBA32{0.2F * static_cast(i), 0.8F, 0.2F, 1.0F}; auto channel = std::make_unique(col, fmt::format("{}", i)); addChild(channel.get()); _channels.push_back(std::move(channel)); } - for (auto i = 0; i < 10; i++) - { - auto col = moci::ColorRGBA32 {0.2F * static_cast(i), 0.8F, 0.2F, 1.0F}; + for (auto i = 0; i < 10; i++) { + auto col = moci::ColorRGBA32{0.2F * static_cast(i), 0.8F, 0.2F, 1.0F}; auto slider = std::make_unique(col); slider->setValue(i / 10.0F); addChild(slider.get()); _sliders.push_back(std::move(slider)); } - for (auto i = 0; i < 20; i++) - { - auto specs = moci::ButtonSpecs {}; + for (auto i = 0; i < 20; i++) { + auto specs = moci::ButtonSpecs{}; specs.callbacks.stateChanged = [](auto state) { moci::ignoreUnused(state); }; auto button = std::make_unique(fmt::format("Test: {}", i), specs); - button->setTextColor(moci::ColorRGBA32 {0.2F * static_cast(i), 0.8F, 0.2F, 1.0F}); + button->setTextColor( + moci::ColorRGBA32{0.2F * static_cast(i), 0.8F, 0.2F, 1.0F} + ); addChild(button.get()); _buttons.push_back(std::move(button)); @@ -108,21 +110,29 @@ class MultiChannel : public moci::Component auto onResize() -> void override { MOCI_PROFILE_FUNCTION(); - auto area = getBounds(); - auto const width = area.getWidth(); - auto buttonArea = area.removeFromRight(width / 3).reduced(20); - auto sliderArea = area.removeFromRight(width / 3).reduced(20); - auto const sliderHeight = static_cast(sliderArea.getHeight() / _sliders.size()); - auto const buttonHeight = static_cast(buttonArea.getHeight() / _buttons.size()); + auto area = getBounds(); + auto const width = area.getWidth(); + auto buttonArea = area.removeFromRight(width / 3).reduced(20); + auto sliderArea = area.removeFromRight(width / 3).reduced(20); + auto const sliderHeight + = static_cast(sliderArea.getHeight() / _sliders.size()); + auto const buttonHeight + = static_cast(buttonArea.getHeight() / _buttons.size()); auto const channelWidth = static_cast(area.getWidth() / _channels.size()); - for (auto& channel : _channels) { channel->setBounds(area.removeFromLeft(channelWidth).reduced(5, 25)); } - for (auto& slider : _sliders) { slider->setBounds(sliderArea.removeFromTop(sliderHeight).reduced(5, 25)); } - for (auto& button : _buttons) { button->setBounds(buttonArea.removeFromTop(buttonHeight).reduced(5, 5)); } + for (auto& channel : _channels) { + channel->setBounds(area.removeFromLeft(channelWidth).reduced(5, 25)); + } + for (auto& slider : _sliders) { + slider->setBounds(sliderArea.removeFromTop(sliderHeight).reduced(5, 25)); + } + for (auto& button : _buttons) { + button->setBounds(buttonArea.removeFromTop(buttonHeight).reduced(5, 5)); + } } private: - moci::DatagramSocket _listener {}; + moci::DatagramSocket _listener{}; std::vector> _channels; std::vector> _sliders; std::vector> _buttons; @@ -131,7 +141,7 @@ class MultiChannel : public moci::Component class Sandbox : public moci::Application { public: - Sandbox() : moci::Application(moci::WindowSpecs {"Sandbox 2D", 1280, 720}) + Sandbox() : moci::Application(moci::WindowSpecs{"Sandbox 2D", 1280, 720}) { MOCI_PROFILE_BEGIN_SESSION("moci-sandbox", "moci-sandbox.json"); getWindow().setFullscreen(true); diff --git a/src/app/sandbox3D/demo_layer.cpp b/src/app/sandbox3D/demo_layer.cpp index 6782f91..8e17d5d 100644 --- a/src/app/sandbox3D/demo_layer.cpp +++ b/src/app/sandbox3D/demo_layer.cpp @@ -18,15 +18,14 @@ #include -namespace -{ +namespace { #if defined(MOCI_API_OPENGL_LEGACY) constexpr auto shaderPrefix = "es2"; #else constexpr auto shaderPrefix = "gl4"; #endif -auto skyboxVertices = std::array { +auto skyboxVertices = std::array{ // positions -1.0F, 1.0F, -1.0F, // -1.0F, -1.0F, -1.0F, // @@ -82,51 +81,66 @@ void DemoLayer::onAttach() auto const numVertices = (_mesh.getVertices().size() * 5) + _floor.getVertices().size(); _vertices.reserve(numVertices); - auto const path = fmt::format("src/app/sandbox3D/assets/shader/{}_general.glsl", shaderPrefix); - _shader = moci::RenderFactory::makeShader(path); + auto const path + = fmt::format("src/app/sandbox3D/assets/shader/{}_general.glsl", shaderPrefix); + _shader = moci::RenderFactory::makeShader(path); _shader->bind(); { MOCI_PROFILE_SCOPE("Translate"); - for (auto const& vertex : _mesh.getVertices()) - { - auto const model = glm::translate(glm::mat4(1.0F), glm::vec3(1.0F)); - auto const scaleMatrix = glm::scale(glm::mat4(1.0F), {_modelScale, _modelScale, _modelScale}); - auto const position = model * scaleMatrix * glm::vec4(vertex.position, 1.0F); - _vertices.push_back({glm::vec3(position), vertex.normal, vertex.color, vertex.texCoord}); + for (auto const& vertex : _mesh.getVertices()) { + auto const model = glm::translate(glm::mat4(1.0F), glm::vec3(1.0F)); + auto const scaleMatrix + = glm::scale(glm::mat4(1.0F), {_modelScale, _modelScale, _modelScale}); + auto const position = model * scaleMatrix * glm::vec4(vertex.position, 1.0F); + _vertices.push_back( + {glm::vec3(position), vertex.normal, vertex.color, vertex.texCoord} + ); } - for (auto x = 1; x <= 5; x++) - { + for (auto x = 1; x <= 5; x++) { auto const modelScale = _modelScale / 2.0F; - auto const rotate = glm::rotate(glm::mat4(1.0F), glm::radians(-90.0F), {1.0F, 0.0F, 0.0F}); - auto const scale = glm::scale(glm::mat4(1.0F), {modelScale, modelScale, modelScale}); - auto const model = glm::translate(glm::mat4(1.0F), glm::vec3((3.0F * x), 5.0F, 1.0F)); - for (auto const& vertex : _mesh.getVertices()) - { - auto const position = model * scale * rotate * glm::vec4(vertex.position, 1.0F); - _vertices.push_back({glm::vec3(position), vertex.normal, vertex.color, vertex.texCoord}); + auto const rotate + = glm::rotate(glm::mat4(1.0F), glm::radians(-90.0F), {1.0F, 0.0F, 0.0F}); + auto const scale + = glm::scale(glm::mat4(1.0F), {modelScale, modelScale, modelScale}); + auto const model + = glm::translate(glm::mat4(1.0F), glm::vec3((3.0F * x), 5.0F, 1.0F)); + for (auto const& vertex : _mesh.getVertices()) { + auto const position + = model * scale * rotate * glm::vec4(vertex.position, 1.0F); + _vertices.push_back( + {glm::vec3(position), vertex.normal, vertex.color, vertex.texCoord} + ); } } - for (auto const& vertex : _floor.getVertices()) - { + for (auto const& vertex : _floor.getVertices()) { auto const model = glm::translate(glm::mat4(1.0F), glm::vec3(1.0F)); auto const scaleMatrix = glm::scale(glm::mat4(1.0F), {5.0F, 5.0F, 5.0F}); auto const position = model * scaleMatrix * glm::vec4(vertex.position, 1.0F); - _vertices.push_back({glm::vec3(position), vertex.normal, {1.0F, 1.0F, 0.5F, 1.0F}, vertex.texCoord}); + _vertices.push_back({ + glm::vec3(position), + vertex.normal, + {1.0F, 1.0F, 0.5F, 1.0F}, + vertex.texCoord + }); } _numVertices = _vertices.size(); } - auto const skyBoxShaderPath = fmt::format("src/app/sandbox3D/assets/shader/{}_skybox.glsl", shaderPrefix); - _skyboxShader = moci::RenderFactory::makeShader(skyBoxShaderPath); + auto const skyBoxShaderPath + = fmt::format("src/app/sandbox3D/assets/shader/{}_skybox.glsl", shaderPrefix); + _skyboxShader = moci::RenderFactory::makeShader(skyBoxShaderPath); _skyboxShader->bind(); _skyboxShader->setInt("u_Skybox", 0); - moci::BufferLayout skyBoxLayout = {{moci::ShaderDataType::Float3, "a_Position"}}; - auto* skyBoxData = reinterpret_cast(skyboxVertices.data()); - auto const skyBoxSize = static_cast(skyboxVertices.size() * sizeof(float)); + moci::BufferLayout skyBoxLayout = { + {moci::ShaderDataType::Float3, "a_Position"} + }; + auto* skyBoxData = reinterpret_cast(skyboxVertices.data()); + auto const skyBoxSize + = static_cast(skyboxVertices.size() * sizeof(float)); _skyboxVbo.reset(moci::RenderFactory::makeVertexBuffer(skyBoxData, skyBoxSize, false)); _skyboxVbo->setLayout(skyBoxLayout); _skyboxVbo->unbind(); @@ -136,7 +150,7 @@ void DemoLayer::onAttach() _skyboxVao->addVertexBuffer(_skyboxVbo); _skyboxVao->setIndexBuffer(_skyboxIbo); _skyboxVao->unbind(); - std::vector faces { + std::vector faces{ std::string("src/app/sandbox3D/assets/textures/skybox/right.jpg"), // std::string("src/app/sandbox3D/assets/textures/skybox/left.jpg"), // std::string("src/app/sandbox3D/assets/textures/skybox/top.jpg"), // @@ -148,13 +162,14 @@ void DemoLayer::onAttach() _skyBoxTexture = moci::RenderFactory::makeTextureCube(faces); moci::BufferLayout layout = { - {moci::ShaderDataType::Float3, "a_Position"}, // - {moci::ShaderDataType::Float3, "a_Normal"}, // - {moci::ShaderDataType::Float4, "a_Color"}, // - {moci::ShaderDataType::Float2, "a_TexCoords"}, // + {moci::ShaderDataType::Float3, "a_Position" }, // + {moci::ShaderDataType::Float3, "a_Normal" }, // + {moci::ShaderDataType::Float4, "a_Color" }, // + {moci::ShaderDataType::Float2, "a_TexCoords"}, // }; - auto* data = reinterpret_cast(_vertices.data()); - auto const size = static_cast(_vertices.size() * sizeof(moci::Mesh::Vertex)); + auto* data = reinterpret_cast(_vertices.data()); + auto const size + = static_cast(_vertices.size() * sizeof(moci::Mesh::Vertex)); _vbo.reset(moci::RenderFactory::makeVertexBuffer(data, size, false)); _vbo->setLayout(layout); _vbo->unbind(); @@ -168,11 +183,17 @@ void DemoLayer::onAttach() // light _light = std::make_unique(); - _textureSolid = moci::RenderFactory::makeTexture2D("src/app/sandbox3D/assets/textures/white_10x10.png"); - _textureColors = moci::RenderFactory::makeTexture2D("src/app/sandbox3D/assets/textures/4color.png"); - _textureColors = moci::RenderFactory::makeTexture2D("src/app/sandbox3D/assets/textures/cerberus_A_4096x4096.png"); + _textureSolid = moci::RenderFactory::makeTexture2D( + "src/app/sandbox3D/assets/textures/white_10x10.png" + ); + _textureColors + = moci::RenderFactory::makeTexture2D("src/app/sandbox3D/assets/textures/4color.png" + ); + _textureColors = moci::RenderFactory::makeTexture2D( + "src/app/sandbox3D/assets/textures/cerberus_A_4096x4096.png" + ); - auto fbSpec = moci::FramebufferSpecs {}; + auto fbSpec = moci::FramebufferSpecs{}; fbSpec.width = 1920; fbSpec.height = 1080; _framebuffer = moci::RenderFactory::makeFramebuffer(fbSpec); @@ -194,8 +215,9 @@ void DemoLayer::onUpdate(moci::Timestep ts) // Camera matrix auto const aspectRatio = _viewportSize.x / _viewportSize.y; - auto const projection = glm::perspective(glm::radians(_cameraFOV), aspectRatio, 0.1F, 100.0F); - auto const view = glm::lookAt( // + auto const projection + = glm::perspective(glm::radians(_cameraFOV), aspectRatio, 0.1F, 100.0F); + auto const view = glm::lookAt( // _cameraPos, // Camera is at (x,y,z), in World Space _cameraPos + _cameraFront, // and looks at _cameraUp // Head is up (set to 0,-1,0 to look upside-down) @@ -213,8 +235,11 @@ void DemoLayer::onUpdate(moci::Timestep ts) _vao->bind(); _textureColors->bind(0); - moci::RenderCommand::drawArrays(moci::RenderDrawMode::Triangles, 0, - static_cast(_vertices.size())); + moci::RenderCommand::drawArrays( + moci::RenderDrawMode::Triangles, + 0, + static_cast(_vertices.size()) + ); _drawStats.numVertices += static_cast(_vertices.size()); _textureColors->unbind(); } @@ -225,7 +250,8 @@ void DemoLayer::onUpdate(moci::Timestep ts) } // skybox - // change depth function so depth test passes when values are equal to depth buffer's content + // change depth function so depth test passes when values are equal to depth buffer's + // content GLCall(glDepthFunc(GL_LEQUAL)); _skyboxShader->bind(); auto const skyboxView = glm::mat4(glm::mat3(view)); @@ -245,12 +271,20 @@ void DemoLayer::onUpdate(moci::Timestep ts) void DemoLayer::onEvent(moci::Event& e) { moci::EventDispatcher dispatcher(e); - dispatcher.dispatch(MOCI_EVENT_METHOD(DemoLayer::onWindowResized)); + dispatcher.dispatch( + MOCI_EVENT_METHOD(DemoLayer::onWindowResized) + ); dispatcher.dispatch(MOCI_EVENT_METHOD(DemoLayer::onKeyPressed)); - dispatcher.dispatch(MOCI_EVENT_METHOD(DemoLayer::onMouseScrolled)); + dispatcher.dispatch( + MOCI_EVENT_METHOD(DemoLayer::onMouseScrolled) + ); dispatcher.dispatch(MOCI_EVENT_METHOD(DemoLayer::onMouseMoved)); - dispatcher.dispatch(MOCI_EVENT_METHOD(DemoLayer::onMousePressed)); - dispatcher.dispatch(MOCI_EVENT_METHOD(DemoLayer::onMouseReleased)); + dispatcher.dispatch( + MOCI_EVENT_METHOD(DemoLayer::onMousePressed) + ); + dispatcher.dispatch( + MOCI_EVENT_METHOD(DemoLayer::onMouseReleased) + ); } bool DemoLayer::onWindowResized(moci::WindowResizeEvent& e) @@ -263,14 +297,16 @@ bool DemoLayer::onWindowResized(moci::WindowResizeEvent& e) bool DemoLayer::onKeyPressed(moci::KeyPressedEvent& e) { auto const cameraSpeed = 0.15F * _lastTimestep; - if (e.getKeyCode() == moci::Key::Up) { _cameraPos += cameraSpeed * _cameraFront; } - if (e.getKeyCode() == moci::Key::Down) { _cameraPos -= cameraSpeed * _cameraFront; } - if (e.getKeyCode() == moci::Key::Left) - { + if (e.getKeyCode() == moci::Key::Up) { + _cameraPos += cameraSpeed * _cameraFront; + } + if (e.getKeyCode() == moci::Key::Down) { + _cameraPos -= cameraSpeed * _cameraFront; + } + if (e.getKeyCode() == moci::Key::Left) { _cameraPos -= glm::normalize(glm::cross(_cameraFront, _cameraUp)) * cameraSpeed; } - if (e.getKeyCode() == moci::Key::Right) - { + if (e.getKeyCode() == moci::Key::Right) { _cameraPos += glm::normalize(glm::cross(_cameraFront, _cameraUp)) * cameraSpeed; } @@ -282,15 +318,18 @@ bool DemoLayer::onMouseScrolled(moci::MouseScrolledEvent& e) _cameraFOV -= e.getYOffset(); constexpr auto minFOV = 1.0F; constexpr auto maxFOV = 75.0F; - if (_cameraFOV < minFOV) { _cameraFOV = minFOV; } - if (_cameraFOV > maxFOV) { _cameraFOV = maxFOV; } + if (_cameraFOV < minFOV) { + _cameraFOV = minFOV; + } + if (_cameraFOV > maxFOV) { + _cameraFOV = maxFOV; + } return true; } bool DemoLayer::onMousePressed(moci::MouseButtonPressedEvent& e) { - if (e.getMouseButton() == moci::MouseCode::ButtonMiddle) - { + if (e.getMouseButton() == moci::MouseCode::ButtonMiddle) { _isMouseDragging = true; return true; } @@ -300,8 +339,7 @@ bool DemoLayer::onMousePressed(moci::MouseButtonPressedEvent& e) bool DemoLayer::onMouseReleased(moci::MouseButtonReleasedEvent& e) { - if (e.getMouseButton() == moci::MouseCode::ButtonMiddle) - { + if (e.getMouseButton() == moci::MouseCode::ButtonMiddle) { _isMouseDragging = false; _firstMouse = true; return true; @@ -312,10 +350,8 @@ bool DemoLayer::onMouseReleased(moci::MouseButtonReleasedEvent& e) bool DemoLayer::onMouseMoved(moci::MouseMovedEvent& e) { - if (_isMouseDragging) - { - if (_firstMouse) - { + if (_isMouseDragging) { + if (_firstMouse) { _cameraLastX = e.getX(); _cameraLastY = e.getY(); _firstMouse = false; @@ -333,14 +369,18 @@ bool DemoLayer::onMouseMoved(moci::MouseMovedEvent& e) _cameraYaw += xOffset; _cameraPitch += yOffset; - if (_cameraPitch > 89.0F) { _cameraPitch = 89.0F; } + if (_cameraPitch > 89.0F) { + _cameraPitch = 89.0F; + } - if (_cameraPitch < -89.0F) { _cameraPitch = -89.0F; } + if (_cameraPitch < -89.0F) { + _cameraPitch = -89.0F; + } - auto front = glm::vec3 {}; - front.x = glm::cos(glm::radians(_cameraYaw)) * glm::cos(glm::radians(_cameraPitch)); - front.y = glm::sin(glm::radians(_cameraPitch)); - front.z = glm::sin(glm::radians(_cameraYaw)) * glm::cos(glm::radians(_cameraPitch)); + auto front = glm::vec3{}; + front.x = glm::cos(glm::radians(_cameraYaw)) * glm::cos(glm::radians(_cameraPitch)); + front.y = glm::sin(glm::radians(_cameraPitch)); + front.z = glm::sin(glm::radians(_cameraYaw)) * glm::cos(glm::radians(_cameraPitch)); _cameraFront = glm::normalize(front); } @@ -351,10 +391,13 @@ void DemoLayer::onImGuiRender() { auto const fps = ImGui::GetIO().Framerate; auto const frameCount = moci::Application::get().getWindow().getFrameCount(); - if (frameCount >= 100) - { - if (fps < _drawStats.minFPS) { _drawStats.minFPS = fps; } - if (fps > _drawStats.maxFPS) { _drawStats.maxFPS = fps; } + if (frameCount >= 100) { + if (fps < _drawStats.minFPS) { + _drawStats.minFPS = fps; + } + if (fps > _drawStats.maxFPS) { + _drawStats.maxFPS = fps; + } } auto const fpsStr = fmt::format("FPS: {0:0.1f}", fps); @@ -362,10 +405,8 @@ void DemoLayer::onImGuiRender() auto const maxFPSStr = fmt::format("Max: {0:0.1f}", _drawStats.maxFPS); auto const ts = fmt::format("Timestep: {0:0.1f}", _lastTimestep); - if (ImGui::BeginMenuBar()) - { - if (ImGui::BeginMenu("Debug")) - { + if (ImGui::BeginMenuBar()) { + if (ImGui::BeginMenu("Debug")) { ImGui::Checkbox("Sandbox3D", &_imguiWindow); ImGui::Checkbox("Imgui Demo", &_imguiDemo); ImGui::Checkbox("Fullscreen", &_fullscreen); @@ -381,51 +422,60 @@ void DemoLayer::onImGuiRender() ImGui::EndMenuBar(); } - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2 {0, 0}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{0, 0}); ImGui::Begin("Viewport"); auto const viewportRegion = imGuiToGlmVec(ImGui::GetContentRegionAvail()); - if (_viewportSize != viewportRegion) - { + if (_viewportSize != viewportRegion) { _viewportSize = viewportRegion; auto const newWidth = static_cast(_viewportSize.x); auto const newHeight = static_cast(_viewportSize.y); _framebuffer->resize(newWidth, newHeight); } - auto* const textureID = reinterpret_cast((size_t)_framebuffer->getColorAttachmentRendererId()); - ImGui::Image(textureID, {viewportRegion.x, viewportRegion.y}, ImVec2(0, 1), ImVec2(1, 0)); + auto* const textureID + = reinterpret_cast((size_t)_framebuffer->getColorAttachmentRendererId()); + ImGui::Image( + textureID, + {viewportRegion.x, viewportRegion.y}, + ImVec2(0, 1), + ImVec2(1, 0) + ); ImGui::End(); ImGui::PopStyleVar(); - if (_imguiWindow) - { + if (_imguiWindow) { ImGui::Begin("Sandbox 3D", &_imguiWindow); - if (ImGui::CollapsingHeader("Camera")) - { + if (ImGui::CollapsingHeader("Camera")) { ImGui::SliderFloat3("Position", glm::value_ptr(_cameraPos), -100.0F, 100.0F); ImGui::SliderFloat3("Look At", glm::value_ptr(_cameraLookAt), -10.0F, 10.0F); ImGui::SliderFloat("FOV", &_cameraFOV, 5.0F, 85.0F); } - if (ImGui::CollapsingHeader("Light")) - { + if (ImGui::CollapsingHeader("Light")) { ImGui::SliderFloat("Ambient", &_ambientLight, 0.0F, 0.4F); - ImGui::SliderFloat3("Light Position", glm::value_ptr(_light->position), -20.0F, 20.0F); + ImGui::SliderFloat3( + "Light Position", + glm::value_ptr(_light->position), + -20.0F, + 20.0F + ); ImGui::ColorEdit4("Light Color", glm::value_ptr(_light->color), 0); ImGui::SliderFloat("Light Scale", &_light->scale, 0.1F, 1.0F); } - if (ImGui::CollapsingHeader("Model")) { ImGui::SliderFloat("Scale", &_modelScale, 0.01F, 20.0F); } + if (ImGui::CollapsingHeader("Model")) { + ImGui::SliderFloat("Scale", &_modelScale, 0.01F, 20.0F); + } - if (ImGui::CollapsingHeader("Stats")) - { + if (ImGui::CollapsingHeader("Stats")) { _fpsHistory.push_back(fps); auto const frameCounter = fmt::format("{} Frames", frameCount); auto const vertices = fmt::format("{} Vertices", _drawStats.numVertices); - auto const triangles = fmt::format("{} Triangles", _drawStats.numVertices / 3); - auto const mb = _drawStats.numVertices * sizeof(moci::Mesh::Vertex) / 1'000'000.0F; - auto const megabyte = fmt::format("{0:0.1f} Mbytes", mb); + auto const triangles = fmt::format("{} Triangles", _drawStats.numVertices / 3); + auto const mb + = _drawStats.numVertices * sizeof(moci::Mesh::Vertex) / 1'000'000.0F; + auto const megabyte = fmt::format("{0:0.1f} Mbytes", mb); ImGui::TextUnformatted(frameCounter.c_str()); ImGui::TextUnformatted(fpsStr.c_str()); ImGui::TextUnformatted(minFPSStr.c_str()); @@ -433,14 +483,25 @@ void DemoLayer::onImGuiRender() ImGui::TextUnformatted(vertices.c_str()); ImGui::TextUnformatted(triangles.c_str()); ImGui::TextUnformatted(megabyte.c_str()); - // auto const lightStr = fmt::format("Light vertices: {}", lightMesh_.getVertices().size()); - // ImGui::TextUnformatted(lightStr.c_str()); + // auto const lightStr = fmt::format("Light vertices: {}", + // lightMesh_.getVertices().size()); ImGui::TextUnformatted(lightStr.c_str()); auto const size = static_cast(_fpsHistory.size()); - ImGui::PlotLines("FPS", _fpsHistory.data(), size, 0, "", 50.0F, 75.0F, ImVec2(0, 80)); + ImGui::PlotLines( + "FPS", + _fpsHistory.data(), + size, + 0, + "", + 50.0F, + 75.0F, + ImVec2(0, 80) + ); } ImGui::End(); } // ImGui Demo - if (_imguiDemo) { ImGui::ShowDemoWindow(&_imguiDemo); } + if (_imguiDemo) { + ImGui::ShowDemoWindow(&_imguiDemo); + } } diff --git a/src/app/sandbox3D/demo_layer.hpp b/src/app/sandbox3D/demo_layer.hpp index 24d6835..2f05dfa 100644 --- a/src/app/sandbox3D/demo_layer.hpp +++ b/src/app/sandbox3D/demo_layer.hpp @@ -36,7 +36,7 @@ class DemoLayer : public moci::Layer bool _fullscreen = false; std::shared_ptr _framebuffer = nullptr; - glm::vec2 _viewportSize = {}; + glm::vec2 _viewportSize = {}; glm::vec3 _cameraPos = {15.0F, 8.70F, 50.0F}; glm::vec3 _cameraFront = {0.0F, 0.0F, -1.0F}; @@ -49,9 +49,9 @@ class DemoLayer : public moci::Layer float _cameraLastY = {_height / 2.0F}; bool _isMouseDragging = false; - glm::vec3 _cameraLookAt = {0.0F, 0.0F, 0.0F}; - float _ambientLight = 0.1F; - float _modelScale = 0.15F; + glm::vec3 _cameraLookAt = {0.0F, 0.0F, 0.0F}; + float _ambientLight = 0.1F; + float _modelScale = 0.15F; std::unique_ptr _light = {}; std::shared_ptr _shader = nullptr; @@ -60,8 +60,8 @@ class DemoLayer : public moci::Layer std::shared_ptr _vao = nullptr; std::size_t _numVertices = {}; - moci::Mesh _mesh {"src/app/sandbox3D/assets/models/cerberus.fbx"}; - moci::Mesh _floor {"src/app/sandbox3D/assets/models/plane.obj"}; + moci::Mesh _mesh{"src/app/sandbox3D/assets/models/cerberus.fbx"}; + moci::Mesh _floor{"src/app/sandbox3D/assets/models/plane.obj"}; std::shared_ptr _textureSolid = {}; std::shared_ptr _textureColors = {}; @@ -77,13 +77,13 @@ class DemoLayer : public moci::Layer // imgui struct DrawStats { - std::uint32_t numVertices {}; + std::uint32_t numVertices{}; float minFPS = 9999.0F; float maxFPS = 0.0F; }; - DrawStats _drawStats = {}; + DrawStats _drawStats = {}; std::vector _fpsHistory = {}; - bool _imguiWindow = true; - bool _imguiDemo = false; + bool _imguiWindow = true; + bool _imguiDemo = false; }; diff --git a/src/app/sandbox3D/main.cpp b/src/app/sandbox3D/main.cpp index 4b51d44..0b01fed 100644 --- a/src/app/sandbox3D/main.cpp +++ b/src/app/sandbox3D/main.cpp @@ -7,7 +7,10 @@ class Sandbox : public moci::Application { public: - Sandbox() : moci::Application {moci::WindowSpecs {"Sandbox 3D", 1920, 1080}} + Sandbox() + : moci::Application{ + moci::WindowSpecs{"Sandbox 3D", 1920, 1080} + } { MOCI_PROFILE_BEGIN_SESSION("moci-sandbox-3d", "moci-sandbox-3d.json"); getWindow().setFullscreen(true); diff --git a/src/app/sandboxOpenGL/assets.hpp b/src/app/sandboxOpenGL/assets.hpp index ab0316a..2df33e4 100644 --- a/src/app/sandboxOpenGL/assets.hpp +++ b/src/app/sandboxOpenGL/assets.hpp @@ -9,20 +9,19 @@ constexpr auto shaderSuffix = "es2"; constexpr auto shaderSuffix = "gl4"; #endif -namespace assets -{ -inline auto quadVertices = std::array { +namespace assets { +inline auto quadVertices = std::array{ -0.75F, -0.75F, 0.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, // 0.75F, -0.75F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, // 0.75F, 0.75F, 0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, 1.0F, // -0.75F, 0.75F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F, 0.0F, 1.0F, // }; -inline auto quadIndices = std::array { - std::uint32_t {0}, // - std::uint32_t {1}, // - std::uint32_t {2}, // - std::uint32_t {0}, // - std::uint32_t {2}, // - std::uint32_t {3}, // +inline auto quadIndices = std::array{ + std::uint32_t{0}, // + std::uint32_t{1}, // + std::uint32_t{2}, // + std::uint32_t{0}, // + std::uint32_t{2}, // + std::uint32_t{3}, // }; } // namespace assets diff --git a/src/app/sandboxOpenGL/main.cpp b/src/app/sandboxOpenGL/main.cpp index 2f665f8..653150a 100644 --- a/src/app/sandboxOpenGL/main.cpp +++ b/src/app/sandboxOpenGL/main.cpp @@ -7,7 +7,10 @@ class Sandbox : public moci::Application { public: - Sandbox() : moci::Application {moci::WindowSpecs {"Sandbox OpenGL", 1920, 1080}} + Sandbox() + : moci::Application{ + moci::WindowSpecs{"Sandbox OpenGL", 1920, 1080} + } { MOCI_PROFILE_BEGIN_SESSION("moci-sandbox-opengl", "moci-sandbox-opengl.json"); // GetWindow().SetFullscreen(true); diff --git a/src/app/sandboxOpenGL/opengl_layer.cpp b/src/app/sandboxOpenGL/opengl_layer.cpp index df698d7..5b5021f 100644 --- a/src/app/sandboxOpenGL/opengl_layer.cpp +++ b/src/app/sandboxOpenGL/opengl_layer.cpp @@ -4,30 +4,34 @@ #include "imgui.h" -namespace -{ +namespace { glm::vec2 imGuiToGlmVec(ImVec2 const& input) { return {input.x, input.y}; } } // namespace + void OpenGLLayer::onAttach() { auto const path = fmt::format("assets/shader/basic_{}.glsl", shaderSuffix); - auto samplers = std::array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + auto samplers = std::array{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; _shader = moci::RenderFactory::makeShader(path); _shader->bind(); _shader->setInts("u_Textures", (int)samplers.size(), samplers.data()); - auto const verticesSize = static_cast(assets::quadVertices.size() * sizeof(float)); - auto layout = moci::BufferLayout { - {moci::ShaderDataType::Float3, "position"}, // - {moci::ShaderDataType::Float4, "color"}, // - {moci::ShaderDataType::Float2, "textureCoord"}, // + auto const verticesSize + = static_cast(assets::quadVertices.size() * sizeof(float)); + auto layout = moci::BufferLayout{ + {moci::ShaderDataType::Float3, "position" }, // + {moci::ShaderDataType::Float4, "color" }, // + {moci::ShaderDataType::Float2, "textureCoord"}, // }; - _vbo.reset(moci::RenderFactory::makeVertexBuffer(assets::quadVertices.data(), verticesSize)); + _vbo.reset( + moci::RenderFactory::makeVertexBuffer(assets::quadVertices.data(), verticesSize) + ); _vbo->setLayout(layout); _vbo->unbind(); - auto indices = std::span {assets::quadIndices.data(), assets::quadIndices.size()}; - auto specs = moci::IndexBufferSpecs {}; + auto indices + = std::span{assets::quadIndices.data(), assets::quadIndices.size()}; + auto specs = moci::IndexBufferSpecs{}; specs.indices = indices; specs.count = static_cast(indices.size()); _ibo.reset(moci::RenderFactory::makeIndexBuffer(specs)); @@ -37,9 +41,11 @@ void OpenGLLayer::onAttach() _vao->setIndexBuffer(_ibo); _vao->unbind(); - _texture = moci::RenderFactory::makeTexture2D("src/app/sandbox3D/assets/textures/skybox/back.jpg"); + _texture = moci::RenderFactory::makeTexture2D( + "src/app/sandbox3D/assets/textures/skybox/back.jpg" + ); - auto fbSpec = moci::FramebufferSpecs {}; + auto fbSpec = moci::FramebufferSpecs{}; fbSpec.width = 1920; fbSpec.height = 1080; _framebuffer = moci::RenderFactory::makeFramebuffer(fbSpec); @@ -52,8 +58,7 @@ void OpenGLLayer::onUpdate(moci::Timestep ts) moci::RenderCommand::setClearColor({0.1F, 0.1F, 0.1F, 1.0F}); moci::RenderCommand::clear(); - if (_framebufferNeedsResize) - { + if (_framebufferNeedsResize) { auto const newWidth = static_cast(_viewportSize.x); auto const newHeight = static_cast(_viewportSize.y); _framebuffer->resize(newWidth, newHeight); @@ -74,16 +79,16 @@ void OpenGLLayer::onImGuiRender() ImGui::Begin("Settings"); ImGui::End(); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2 {0, 0}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{0, 0}); ImGui::Begin("Viewport"); auto const viewportRegion = imGuiToGlmVec(ImGui::GetContentRegionAvail()); - if (_viewportSize != viewportRegion) - { + if (_viewportSize != viewportRegion) { _viewportSize = viewportRegion; _framebufferNeedsResize = true; } - auto* const textureID = reinterpret_cast((size_t)_framebuffer->getColorAttachmentRendererId()); + auto* const textureID + = reinterpret_cast((size_t)_framebuffer->getColorAttachmentRendererId()); ImGui::Image(textureID, {_viewportSize.x, _viewportSize.y}, ImVec2(0, 1), ImVec2(1, 0)); ImGui::End(); ImGui::PopStyleVar(); @@ -92,12 +97,24 @@ void OpenGLLayer::onImGuiRender() void OpenGLLayer::onEvent(moci::Event& e) { moci::EventDispatcher dispatcher(e); - dispatcher.dispatch(MOCI_EVENT_METHOD(OpenGLLayer::handleWindowResized)); - dispatcher.dispatch(MOCI_EVENT_METHOD(OpenGLLayer::handleKeyPressed)); - dispatcher.dispatch(MOCI_EVENT_METHOD(OpenGLLayer::handleMouseScrolled)); - dispatcher.dispatch(MOCI_EVENT_METHOD(OpenGLLayer::handleMouseMoved)); - dispatcher.dispatch(MOCI_EVENT_METHOD(OpenGLLayer::handleMousePressed)); - dispatcher.dispatch(MOCI_EVENT_METHOD(OpenGLLayer::handleMouseReleased)); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OpenGLLayer::handleWindowResized) + ); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OpenGLLayer::handleKeyPressed) + ); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OpenGLLayer::handleMouseScrolled) + ); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OpenGLLayer::handleMouseMoved) + ); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OpenGLLayer::handleMousePressed) + ); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OpenGLLayer::handleMouseReleased) + ); } bool OpenGLLayer::handleWindowResized(moci::WindowResizeEvent& e) diff --git a/src/app/tools/embed-resources/test/main.cpp b/src/app/tools/embed-resources/test/main.cpp index 804ee0a..943953d 100644 --- a/src/app/tools/embed-resources/test/main.cpp +++ b/src/app/tools/embed-resources/test/main.cpp @@ -4,11 +4,14 @@ int main() { - auto const shaderSource = std::string {moci::resources::basic_gl4, moci::resources::basic_gl4_len}; - auto line = std::string {}; - auto input = std::istringstream {shaderSource}; + auto const shaderSource + = std::string{moci::resources::basic_gl4, moci::resources::basic_gl4_len}; + auto line = std::string{}; + auto input = std::istringstream{shaderSource}; - while (getline(input, line)) { std::printf("%s\n", line.c_str()); } + while (getline(input, line)) { + std::printf("%s\n", line.c_str()); + } return 0; } diff --git a/src/app/tools/model-viewer/main.cpp b/src/app/tools/model-viewer/main.cpp index c16dea7..bf63447 100644 --- a/src/app/tools/model-viewer/main.cpp +++ b/src/app/tools/model-viewer/main.cpp @@ -20,7 +20,7 @@ class MociModelViwerLayer : public moci::Layer MociModelViwerLayer() = default; ~MociModelViwerLayer() override = default; - void OnAttach() override { } + void OnAttach() override {} void OnUpdate(moci::Timestep ts) override { @@ -30,19 +30,24 @@ class MociModelViwerLayer : public moci::Layer moci::RenderCommand::Clear(); // // Camera matrix - // glm::mat4 const projection = glm::perspective(glm::radians(cameraFOV_), width_ / height_, 0.1f, 100.0f); - // glm::mat4 const view = glm::lookAt( // + // glm::mat4 const projection = glm::perspective(glm::radians(cameraFOV_), width_ / + // height_, 0.1f, 100.0f); glm::mat4 const view = glm::lookAt( // // cameraPos_, // Camera is at (x,y,z), in World Space // cameraLookAt_, // and looks at the origin - // glm::vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look upside-down) + // glm::vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look + // upside-down) // ); } void OnEvent(moci::Event& e) override { moci::EventDispatcher dispatcher(e); - dispatcher.Dispatch(MOCI_EVENT_METHOD(MociModelViwerLayer::OnWindowResized)); - dispatcher.Dispatch(MOCI_EVENT_METHOD(MociModelViwerLayer::OnKeyPressed)); + dispatcher.Dispatch( + MOCI_EVENT_METHOD(MociModelViwerLayer::OnWindowResized) + ); + dispatcher.Dispatch( + MOCI_EVENT_METHOD(MociModelViwerLayer::OnKeyPressed) + ); } bool OnWindowResized(moci::WindowResizeEvent& e) @@ -61,10 +66,13 @@ class MociModelViwerLayer : public moci::Layer void OnImGuiRender() override { auto const fps = ImGui::GetIO().Framerate; - if (drawStats_.frameCounter++ >= 100) - { - if (fps < drawStats_.minFPS) { drawStats_.minFPS = fps; } - if (fps > drawStats_.maxFPS) { drawStats_.maxFPS = fps; } + if (drawStats_.frameCounter++ >= 100) { + if (fps < drawStats_.minFPS) { + drawStats_.minFPS = fps; + } + if (fps > drawStats_.maxFPS) { + drawStats_.maxFPS = fps; + } } auto const fpsStr = fmt::format("FPS: {0:0.1f}", fps); @@ -72,10 +80,8 @@ class MociModelViwerLayer : public moci::Layer auto const maxFPSStr = fmt::format("Max: {0:0.1f}", drawStats_.maxFPS); auto const ts = fmt::format("Timestep: {0:0.1f}", lastTimestep_); - if (ImGui::BeginMenuBar()) - { - if (ImGui::BeginMenu("Debug")) - { + if (ImGui::BeginMenuBar()) { + if (ImGui::BeginMenu("Debug")) { ImGui::Checkbox("Sandbox3D", &imguiWindow_); ImGui::Checkbox("Imgui Demo", &imguiDemo_); ImGui::Checkbox("Fullscreen", &fullscreen_); @@ -90,17 +96,16 @@ class MociModelViwerLayer : public moci::Layer ImGui::TextUnformatted(ts.c_str()); ImGui::EndMenuBar(); } - if (imguiWindow_) - { + if (imguiWindow_) { ImGui::Begin("Model Viewer", &imguiWindow_); - if (ImGui::CollapsingHeader("Stats")) - { + if (ImGui::CollapsingHeader("Stats")) { // fpsHistory_.push_back(fps); auto const frameCount = fmt::format("{} Frames", drawStats_.frameCounter); - // auto const vertices = fmt::format("{} Vertices", drawStats_.numVertices); - // auto const triangles = fmt::format("{} Triangles", drawStats_.numVertices / 3); - // auto const mb = drawStats_.numVertices * sizeof(Vertex) / 1'000'000.0f; - // auto const megabyte = fmt::format("{0:0.1f} Mbytes", mb); + // auto const vertices = fmt::format("{} Vertices", + // drawStats_.numVertices); auto const triangles = fmt::format("{} + // Triangles", drawStats_.numVertices / 3); auto const mb = + // drawStats_.numVertices * sizeof(Vertex) / 1'000'000.0f; auto const + // megabyte = fmt::format("{0:0.1f} Mbytes", mb); ImGui::TextUnformatted(frameCount.c_str()); // ImGui::TextUnformatted(fpsStr.c_str()); // ImGui::TextUnformatted(minFPSStr.c_str()); @@ -108,16 +113,19 @@ class MociModelViwerLayer : public moci::Layer // ImGui::TextUnformatted(vertices.c_str()); // ImGui::TextUnformatted(triangles.c_str()); // ImGui::TextUnformatted(megabyte.c_str()); - // auto const lightStr = fmt::format("Light vertices: {}", lightMesh_.getVertices().size()); - // ImGui::TextUnformatted(lightStr.c_str()); - // auto const size = static_cast(fpsHistory_.size()); - // ImGui::PlotLines("FPS", fpsHistory_.data(), size, 0, "", 50.0f, 75.0f, ImVec2(0, 80)); + // auto const lightStr = fmt::format("Light vertices: {}", + // lightMesh_.getVertices().size()); + // ImGui::TextUnformatted(lightStr.c_str()); auto const size = + // static_cast(fpsHistory_.size()); ImGui::PlotLines("FPS", + // fpsHistory_.data(), size, 0, "", 50.0f, 75.0f, ImVec2(0, 80)); } ImGui::End(); } // ImGui Demo - if (imguiDemo_) { ImGui::ShowDemoWindow(&imguiDemo_); } + if (imguiDemo_) { + ImGui::ShowDemoWindow(&imguiDemo_); + } } public: @@ -131,22 +139,22 @@ class MociModelViwerLayer : public moci::Layer std::shared_ptr ibo_ = nullptr; std::shared_ptr vao_ = nullptr; - std::size_t numVertices_ {}; + std::size_t numVertices_{}; // imgui struct DrawStats { - std::uint32_t frameCounter {}; - std::uint32_t numVertices {}; + std::uint32_t frameCounter{}; + std::uint32_t numVertices{}; float minFPS = 9999.0f; float maxFPS = 0.0f; }; - DrawStats drawStats_ {}; + DrawStats drawStats_{}; std::vector fpsHistory_ = {}; - bool imguiWindow_ = true; - bool imguiDemo_ = false; + bool imguiWindow_ = true; + bool imguiDemo_ = false; }; class MociModelViwerApp : public moci::Application diff --git a/src/moci/application/application.cpp b/src/moci/application/application.cpp index 00fd218..da50583 100644 --- a/src/moci/application/application.cpp +++ b/src/moci/application/application.cpp @@ -5,12 +5,11 @@ #include #include -namespace moci -{ +namespace moci { Application* Application::sInstance = nullptr; -Application::Application() : Application(WindowSpecs {}) { } +Application::Application() : Application(WindowSpecs{}) {} Application::Application(WindowSpecs windowSpecs) { @@ -32,16 +31,17 @@ Application::Application(WindowSpecs windowSpecs) void Application::pushLayer(Layer::Ptr&& layer) { _layerStack.pushLayer(std::move(layer)); } -void Application::pushOverlay(Layer::Ptr&& layer) { _layerStack.pushOverlay(std::move(layer)); } +void Application::pushOverlay(Layer::Ptr&& layer) +{ + _layerStack.pushOverlay(std::move(layer)); +} void Application::onEvent(Event& e) { - if (e.getEventType() == EventType::KeyPressed) - { + if (e.getEventType() == EventType::KeyPressed) { auto* keyEvent = dynamic_cast(&e); - if (keyEvent->getKeyCode() == Key::Escape) - { - auto closeEvent = WindowCloseEvent {}; + if (keyEvent->getKeyCode() == Key::Escape) { + auto closeEvent = WindowCloseEvent{}; onWindowClose(closeEvent); } } @@ -50,34 +50,39 @@ void Application::onEvent(Event& e) dispatcher.dispatch(MOCI_EVENT_METHOD(onWindowClose)); dispatcher.dispatch(MOCI_EVENT_METHOD(onWindowResize)); - for (auto it = _layerStack.end(); it != _layerStack.begin();) - { + for (auto it = _layerStack.end(); it != _layerStack.begin();) { (*--it)->onEvent(e); - if (e.Handled) { break; } + if (e.Handled) { + break; + } } } void Application::run() { using namespace std::chrono; - while (_running) - { + while (_running) { MOCI_PROFILE_SCOPE("App::Run::Loop"); - auto const now = steady_clock::now(); - auto const elapsedTime = time_point_cast(now).time_since_epoch() - - time_point_cast(_lastFrameTimepoint).time_since_epoch(); - auto const timestep = Timestep {static_cast(elapsedTime.count()) / 1'000.0F / 1'000.0F}; + auto const now = steady_clock::now(); + auto const elapsedTime + = time_point_cast(now).time_since_epoch() + - time_point_cast(_lastFrameTimepoint).time_since_epoch(); + auto const timestep + = Timestep{static_cast(elapsedTime.count()) / 1'000.0F / 1'000.0F}; _lastFrameTimepoint = now; - if (!_minimized) - { - for (auto& layer : _layerStack) { layer->onUpdate(timestep); } + if (!_minimized) { + for (auto& layer : _layerStack) { + layer->onUpdate(timestep); + } } { MOCI_PROFILE_SCOPE("App::Run::Loop::ImGui"); moci::ImGuiLayer::begin(); - for (auto& layer : _layerStack) { layer->onImGuiRender(); } + for (auto& layer : _layerStack) { + layer->onImGuiRender(); + } moci::ImGuiLayer::end(); } @@ -97,8 +102,7 @@ auto Application::onWindowClose(WindowCloseEvent& e) -> bool auto Application::onWindowResize(WindowResizeEvent& e) -> bool { - if (e.getWidth() == 0 || e.getHeight() == 0) - { + if (e.getWidth() == 0 || e.getHeight() == 0) { _minimized = true; return false; } diff --git a/src/moci/application/application.hpp b/src/moci/application/application.hpp index 35b761f..4327ffb 100644 --- a/src/moci/application/application.hpp +++ b/src/moci/application/application.hpp @@ -13,8 +13,7 @@ auto main(int argc, char** argv) -> int; -namespace moci -{ +namespace moci { class Application { @@ -39,7 +38,7 @@ class Application auto onWindowClose(WindowCloseEvent& e) -> bool; auto onWindowResize(WindowResizeEvent& e) -> bool; - std::unique_ptr _window = nullptr; + std::unique_ptr _window = nullptr; bool _running = true; bool _minimized = false; LayerStack _layerStack = {}; diff --git a/src/moci/application/entry_point.hpp b/src/moci/application/entry_point.hpp index 24af19f..ba0c382 100644 --- a/src/moci/application/entry_point.hpp +++ b/src/moci/application/entry_point.hpp @@ -2,10 +2,10 @@ #if defined(MOCI_WINDOWS) || defined(MOCI_MAC) || defined(MOCI_LINUX) -#include + #include -#include -#include + #include + #include extern moci::Application* moci::createApplication(); diff --git a/src/moci/application/glfw/input.cpp b/src/moci/application/glfw/input.cpp index c162024..9b39a21 100644 --- a/src/moci/application/glfw/input.cpp +++ b/src/moci/application/glfw/input.cpp @@ -3,36 +3,38 @@ #include #if not defined(MOCI_API_OPENGL_ES) -#include + #include #endif #include #include -namespace moci -{ +namespace moci { std::unique_ptr Input::sInstance = std::make_unique(); auto GlfwInput::isKeyPressedImpl(Key keycode) -> bool { - auto* window = static_cast(Application::get().getWindow().getNativeWindow()); - auto state = glfwGetKey(window, static_cast(keycode)); + auto* window + = static_cast(Application::get().getWindow().getNativeWindow()); + auto state = glfwGetKey(window, static_cast(keycode)); return state == GLFW_PRESS || state == GLFW_REPEAT; } auto GlfwInput::isMouseButtonPressedImpl(MouseCode button) -> bool { - auto* window = static_cast(Application::get().getWindow().getNativeWindow()); - auto state = glfwGetMouseButton(window, static_cast(button)); + auto* window + = static_cast(Application::get().getWindow().getNativeWindow()); + auto state = glfwGetMouseButton(window, static_cast(button)); return state == GLFW_PRESS; } auto GlfwInput::getMousePositionImpl() -> std::pair { - auto* window = static_cast(Application::get().getWindow().getNativeWindow()); - double xpos = NAN; + auto* window + = static_cast(Application::get().getWindow().getNativeWindow()); + double xpos = NAN; double ypos = NAN; glfwGetCursorPos(window, &xpos, &ypos); diff --git a/src/moci/application/glfw/input.hpp b/src/moci/application/glfw/input.hpp index 0666cd5..4366dfa 100644 --- a/src/moci/application/glfw/input.hpp +++ b/src/moci/application/glfw/input.hpp @@ -5,8 +5,7 @@ #include -namespace moci -{ +namespace moci { class GlfwInput : public Input { diff --git a/src/moci/application/glfw/window.cpp b/src/moci/application/glfw/window.cpp index 7ce5bd5..4b576a4 100644 --- a/src/moci/application/glfw/window.cpp +++ b/src/moci/application/glfw/window.cpp @@ -5,17 +5,19 @@ #include #include -namespace moci -{ +namespace moci { static uint8_t sGlfwWindowCount = 0; -static void glfwErrorCallback(int error, const char* description) +static void glfwErrorCallback(int error, char const* description) { MOCI_CORE_ERROR("GLFW Error ({0}): {1}", error, description); } -auto Window::create(WindowSpecs props) -> Window* { return new GlfwWindow(std::move(props)); } +auto Window::create(WindowSpecs props) -> Window* +{ + return new GlfwWindow(std::move(props)); +} GlfwWindow::GlfwWindow(WindowSpecs props) { init(std::move(props)); } @@ -27,8 +29,7 @@ void GlfwWindow::init(WindowSpecs props) _data.Width = props.Width; _data.Height = props.Height; - if (sGlfwWindowCount == 0) - { + if (sGlfwWindowCount == 0) { MOCI_CORE_INFO("Initializing GLFW"); int success = glfwInit(); MOCI_CORE_ASSERT(success, "Could not intialize GLFW!"); @@ -40,23 +41,28 @@ void GlfwWindow::init(WindowSpecs props) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); #else -#if defined(MOCI_MAC) + #if defined(MOCI_MAC) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); -#else + #else glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); -#endif + #endif #endif auto const width = static_cast(_data.Width); auto const height = static_cast(_data.Height); - _window = glfwCreateWindow(width, height, _data.Title.c_str(), nullptr, nullptr); + _window = glfwCreateWindow(width, height, _data.Title.c_str(), nullptr, nullptr); ++sGlfwWindowCount; - MOCI_CORE_INFO("Creating window {0} ({1}, {2})", props.Title, props.Width, props.Height); + MOCI_CORE_INFO( + "Creating window {0} ({1}, {2})", + props.Title, + props.Width, + props.Height + ); _context = std::unique_ptr(GraphicsContext::create(_window)); _context->init(); @@ -65,112 +71,96 @@ void GlfwWindow::init(WindowSpecs props) setVSync(true); // Set GLFW callbacks - glfwSetWindowSizeCallback(_window, - [](GLFWwindow* window, int width, int height) - { - WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); - data.Width = width; - data.Height = height; - - WindowResizeEvent event(width, height); - data.EventCallback(event); - }); - - glfwSetWindowCloseCallback(_window, - [](GLFWwindow* window) - { - WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); - WindowCloseEvent event; - data.EventCallback(event); - }); - - glfwSetKeyCallback(_window, - [](GLFWwindow* window, int glfwKey, int scancode, int action, int mods) - { - ignoreUnused(scancode); - ignoreUnused(mods); - - WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); - auto const key = static_cast(glfwKey); - switch (action) - { - case GLFW_PRESS: - { - KeyPressedEvent event(key, 0); - data.EventCallback(event); - break; - } - case GLFW_RELEASE: - { - KeyReleasedEvent event(key); - data.EventCallback(event); - break; - } - case GLFW_REPEAT: - { - KeyPressedEvent event(key, 1); - data.EventCallback(event); - break; - } - } - }); - - glfwSetCharCallback(_window, - [](GLFWwindow* window, unsigned int glfwKeyCode) - { - auto event = KeyTypedEvent {static_cast(glfwKeyCode)}; - auto& data = *static_cast(glfwGetWindowUserPointer(window)); - data.EventCallback(event); - }); - - glfwSetMouseButtonCallback(_window, - [](GLFWwindow* window, int button, int action, int mods) - { - ignoreUnused(mods); - auto& data = *static_cast(glfwGetWindowUserPointer(window)); - - switch (action) - { - case GLFW_PRESS: - { - MouseButtonPressedEvent event(static_cast(button)); - data.EventCallback(event); - break; - } - case GLFW_RELEASE: - { - MouseButtonReleasedEvent event(static_cast(button)); - data.EventCallback(event); - break; - } - } - }); - - glfwSetScrollCallback(_window, - [](GLFWwindow* window, double xOffset, double yOffset) - { - WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); - - MouseScrolledEvent event((float)xOffset, (float)yOffset); - data.EventCallback(event); - }); - - glfwSetCursorPosCallback(_window, - [](GLFWwindow* window, double xPos, double yPos) - { - WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); - - MouseMovedEvent event((float)xPos, (float)yPos); - data.EventCallback(event); - }); + glfwSetWindowSizeCallback(_window, [](GLFWwindow* window, int width, int height) { + WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); + data.Width = width; + data.Height = height; + + WindowResizeEvent event(width, height); + data.EventCallback(event); + }); + + glfwSetWindowCloseCallback(_window, [](GLFWwindow* window) { + WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); + WindowCloseEvent event; + data.EventCallback(event); + }); + + glfwSetKeyCallback( + _window, + [](GLFWwindow* window, int glfwKey, int scancode, int action, int mods) { + ignoreUnused(scancode); + ignoreUnused(mods); + + WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); + auto const key = static_cast(glfwKey); + switch (action) { + case GLFW_PRESS: { + KeyPressedEvent event(key, 0); + data.EventCallback(event); + break; + } + case GLFW_RELEASE: { + KeyReleasedEvent event(key); + data.EventCallback(event); + break; + } + case GLFW_REPEAT: { + KeyPressedEvent event(key, 1); + data.EventCallback(event); + break; + } + } + } + ); + + glfwSetCharCallback(_window, [](GLFWwindow* window, unsigned int glfwKeyCode) { + auto event = KeyTypedEvent{static_cast(glfwKeyCode)}; + auto& data = *static_cast(glfwGetWindowUserPointer(window)); + data.EventCallback(event); + }); + + glfwSetMouseButtonCallback( + _window, + [](GLFWwindow* window, int button, int action, int mods) { + ignoreUnused(mods); + auto& data = *static_cast(glfwGetWindowUserPointer(window)); + + switch (action) { + case GLFW_PRESS: { + MouseButtonPressedEvent event(static_cast(button)); + data.EventCallback(event); + break; + } + case GLFW_RELEASE: { + MouseButtonReleasedEvent event(static_cast(button)); + data.EventCallback(event); + break; + } + } + } + ); + + glfwSetScrollCallback(_window, [](GLFWwindow* window, double xOffset, double yOffset) { + WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); + + MouseScrolledEvent event((float)xOffset, (float)yOffset); + data.EventCallback(event); + }); + + glfwSetCursorPosCallback(_window, [](GLFWwindow* window, double xPos, double yPos) { + WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); + + MouseMovedEvent event((float)xPos, (float)yPos); + data.EventCallback(event); + }); } void GlfwWindow::shutdown() { glfwDestroyWindow(_window); - if (--sGlfwWindowCount == 0) - { + if (--sGlfwWindowCount == 0) { MOCI_CORE_INFO("Terminating GLFW"); glfwTerminate(); } @@ -185,8 +175,11 @@ void GlfwWindow::onUpdate() void GlfwWindow::setVSync(bool enabled) { - if (enabled) { glfwSwapInterval(1); } - else { glfwSwapInterval(0); } + if (enabled) { + glfwSwapInterval(1); + } else { + glfwSwapInterval(0); + } _data.VSync = enabled; } @@ -195,11 +188,12 @@ auto GlfwWindow::isVSync() const -> bool { return _data.VSync; } void GlfwWindow::setFullscreen(bool enabled) { - if (isFullscreen() == enabled) { return; } + if (isFullscreen() == enabled) { + return; + } MOCI_CORE_INFO("Setting window fullscreen to {}", enabled); - if (enabled) - { + if (enabled) { // backup window position and window size auto x = 0; auto y = 0; @@ -214,11 +208,17 @@ void GlfwWindow::setFullscreen(bool enabled) // switch to full screen glfwSetWindowMonitor(_window, monitor, 0, 0, mode->width, mode->height, 0); - } - else - { + } else { // restore last window size and position - glfwSetWindowMonitor(_window, nullptr, _data.Position[0], _data.Position[1], _data.Width, _data.Height, 0); + glfwSetWindowMonitor( + _window, + nullptr, + _data.Position[0], + _data.Position[1], + _data.Width, + _data.Height, + 0 + ); } _data.Fullscreen = enabled; diff --git a/src/moci/application/glfw/window.hpp b/src/moci/application/glfw/window.hpp index 92f8068..9c559be 100644 --- a/src/moci/application/glfw/window.hpp +++ b/src/moci/application/glfw/window.hpp @@ -6,12 +6,12 @@ #include #if MOCI_API_OPENGL_ES -#define GLFW_INCLUDE_ES2 -#define IMGUI_IMPL_OPENGL_ES2 -#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM + #define GLFW_INCLUDE_ES2 + #define IMGUI_IMPL_OPENGL_ES2 + #define IMGUI_IMPL_OPENGL_LOADER_CUSTOM #else -#define IMGUI_IMPL_OPENGL_LOADER_GLEW -#include + #define IMGUI_IMPL_OPENGL_LOADER_GLEW + #include #endif #include @@ -19,8 +19,7 @@ #include #include -namespace moci -{ +namespace moci { class GlfwWindow : public Window { @@ -30,18 +29,32 @@ class GlfwWindow : public Window void onUpdate() override; - [[nodiscard]] inline auto getWidth() const -> unsigned int override { return _data.Width; } - [[nodiscard]] inline auto getHeight() const -> unsigned int override { return _data.Height; } + [[nodiscard]] inline auto getWidth() const -> unsigned int override + { + return _data.Width; + } + + [[nodiscard]] inline auto getHeight() const -> unsigned int override + { + return _data.Height; + } // Window attributes - inline void setEventCallback(const EventCallbackFn& callback) override { _data.EventCallback = callback; } + inline void setEventCallback(EventCallbackFn const& callback) override + { + _data.EventCallback = callback; + } + void setVSync(bool enabled) override; [[nodiscard]] auto isVSync() const -> bool override; void setFullscreen(bool enabled) override; [[nodiscard]] auto isFullscreen() const -> bool override; - [[nodiscard]] auto getFrameCount() const noexcept -> std::uint32_t override { return _frameCounter; } + [[nodiscard]] auto getFrameCount() const noexcept -> std::uint32_t override + { + return _frameCounter; + } [[nodiscard]] inline auto getNativeWindow() const -> void* override { return _window; } @@ -49,22 +62,22 @@ class GlfwWindow : public Window virtual void init(WindowSpecs props); virtual void shutdown(); - GLFWwindow* _window {}; + GLFWwindow* _window{}; std::unique_ptr _context; struct WindowData { std::string Title; - unsigned int Width {}, Height {}; - std::array Position {}; - bool VSync {}; - bool Fullscreen {}; + unsigned int Width{}, Height{}; + std::array Position{}; + bool VSync{}; + bool Fullscreen{}; EventCallbackFn EventCallback; }; WindowData _data; - std::uint32_t _frameCounter {}; + std::uint32_t _frameCounter{}; }; } // namespace moci diff --git a/src/moci/application/window.hpp b/src/moci/application/window.hpp index a67c59d..c447543 100644 --- a/src/moci/application/window.hpp +++ b/src/moci/application/window.hpp @@ -6,8 +6,7 @@ #include -namespace moci -{ +namespace moci { struct WindowSpecs { @@ -15,10 +14,15 @@ struct WindowSpecs unsigned int Width; unsigned int Height; - explicit WindowSpecs(std::string title = "moci engine", unsigned int width = 1280, unsigned int height = 1024) - : Title(std::move(title)), Width(width), Height(height) - { - } + explicit WindowSpecs( + std::string title = "moci engine", + unsigned int width = 1280, + unsigned int height = 1024 + ) + : Title(std::move(title)) + , Width(width) + , Height(height) + {} }; // Interface representing a desktop system based Window @@ -37,7 +41,7 @@ class Window [[nodiscard]] virtual auto getHeight() const -> unsigned int = 0; // Window attributes - virtual void setEventCallback(const EventCallbackFn& callback) = 0; + virtual void setEventCallback(EventCallbackFn const& callback) = 0; virtual void setVSync(bool enabled) = 0; [[nodiscard]] virtual auto isVSync() const -> bool = 0; diff --git a/src/moci/core/benchmark/benchmark.hpp b/src/moci/core/benchmark/benchmark.hpp index e9271cf..1fe07a8 100644 --- a/src/moci/core/benchmark/benchmark.hpp +++ b/src/moci/core/benchmark/benchmark.hpp @@ -4,20 +4,21 @@ #include -namespace moci -{ +namespace moci { #ifdef _MSC_VER -#pragma optimize("", off) -inline void DoNotOptimizeDependencySink(const void*) { } -#pragma optimize("", on) + #pragma optimize("", off) + +inline void DoNotOptimizeDependencySink(void const*) {} + + #pragma optimize("", on) /** * @brief Useful for writting benchmarks */ template -void DoNotOptimizeAway(const T& datum) +void DoNotOptimizeAway(T const& datum) { DoNotOptimizeDependencySink(&datum); } @@ -28,7 +29,7 @@ void DoNotOptimizeAway(const T& datum) * @brief Useful for writting benchmarks */ template -auto DoNotOptimizeAway(const T& datum) -> void +auto DoNotOptimizeAway(T const& datum) -> void { // This version of DoNotOptimizeAway tells the compiler that the asm // block will read datum from memory, and that in addition it might read @@ -45,13 +46,17 @@ template class ExecutionTimer final { public: - using Clock = std::conditional_t; + using Clock = std::conditional_t< + std::chrono::high_resolution_clock::is_steady, + std::chrono::high_resolution_clock, + std::chrono::steady_clock>; ExecutionTimer() = default; + ~ExecutionTimer() { - auto const micros = std::chrono::duration_cast(Clock::now() - mStart).count(); + auto const micros + = std::chrono::duration_cast(Clock::now() - mStart).count(); MOCI_CORE_INFO("Elapsed: {}μs", micros); } diff --git a/src/moci/core/benchmark/profile.hpp b/src/moci/core/benchmark/profile.hpp index 846d113..07597fb 100644 --- a/src/moci/core/benchmark/profile.hpp +++ b/src/moci/core/benchmark/profile.hpp @@ -13,8 +13,7 @@ #include #include -namespace moci -{ +namespace moci { using FloatingPointMicroseconds = std::chrono::duration; @@ -36,7 +35,7 @@ class Instrumentor { private: std::mutex _mutex; - std::unique_ptr _currentSession {nullptr}; + std::unique_ptr _currentSession{nullptr}; std::ofstream _outputStream; std::vector _buffer; @@ -46,16 +45,18 @@ class Instrumentor void beginSession(std::string const& name, std::string const& filepath = "results.json") { std::lock_guard lock(_mutex); - if (_currentSession != nullptr) - { - // If there is already a current session, then close it before beginning new one. - // Subsequent profiling output meant for the original session will end up in the - // newly opened session instead. That's better than having badly formatted - // profiling output. - if (Log::getCoreLogger()) - { // Edge case: BeginSession() might be before Log::Init() - MOCI_CORE_ERROR("Instrumentor::BeginSession('{0}') when session '{1}' already open.", name, - _currentSession->Name); + if (_currentSession != nullptr) { + // If there is already a current session, then close it before beginning new + // one. Subsequent profiling output meant for the original session will end up + // in the newly opened session instead. That's better than having badly + // formatted profiling output. + if (Log::getCoreLogger( + )) { // Edge case: BeginSession() might be before Log::Init() + MOCI_CORE_ERROR( + "Instrumentor::BeginSession('{0}') when session '{1}' already open.", + name, + _currentSession->Name + ); } internalEndSession(); } @@ -63,17 +64,17 @@ class Instrumentor _buffer.reserve(1'000'000); _outputStream.open(filepath); - if (_outputStream.is_open()) - { + if (_outputStream.is_open()) { _currentSession = std::make_unique(); _currentSession->Name = name; writeHeader(); - } - else - { - if (Log::getCoreLogger()) - { // Edge case: BeginSession() might be before Log::Init() - MOCI_CORE_ERROR("Instrumentor could not open results file '{0}'.", filepath); + } else { + if (Log::getCoreLogger( + )) { // Edge case: BeginSession() might be before Log::Init() + MOCI_CORE_ERROR( + "Instrumentor could not open results file '{0}'.", + filepath + ); } } } @@ -84,21 +85,23 @@ class Instrumentor internalEndSession(); } - void writeProfile(const ProfileResult& result) + void writeProfile(ProfileResult const& result) { auto name = result.Name; std::replace(name.begin(), name.end(), '"', '\''); - auto const json = fmt::format( // + auto const json = fmt::format( // R"(,{{"cat":"function","dur": {0},"name": "{1}","ph":"X","pid":0,"tid": "{2}","ts": {3}}})", // - result.ElapsedTime.count(), // - name, // - fmt::streamed(result.ThreadID), // - result.Start.count() // + result.ElapsedTime.count(), // + name, // + fmt::streamed(result.ThreadID), // + result.Start.count() // ); std::lock_guard lock(_mutex); - if (_currentSession != nullptr) { _buffer.push_back(json); } + if (_currentSession != nullptr) { + _buffer.push_back(json); + } } static auto get() -> Instrumentor& @@ -125,9 +128,10 @@ class Instrumentor void internalEndSession() { - if (_currentSession != nullptr) - { - for (auto const& item : _buffer) { _outputStream << item; } + if (_currentSession != nullptr) { + for (auto const& item : _buffer) { + _outputStream << item; + } _outputStream.flush(); writeFooter(); @@ -141,45 +145,53 @@ class Instrumentor class InstrumentationTimer { public: - explicit InstrumentationTimer(const char* name) : _name(name) + explicit InstrumentationTimer(char const* name) : _name(name) { _startTimepoint = std::chrono::steady_clock::now(); } ~InstrumentationTimer() { - if (!_stopped) { stop(); } + if (!_stopped) { + stop(); + } } void stop() { auto endTimepoint = std::chrono::steady_clock::now(); - auto highResStart = FloatingPointMicroseconds {_startTimepoint.time_since_epoch()}; + auto highResStart = FloatingPointMicroseconds{_startTimepoint.time_since_epoch()}; auto elapsedTime - = std::chrono::time_point_cast(endTimepoint).time_since_epoch() - - std::chrono::time_point_cast(_startTimepoint).time_since_epoch(); + = std::chrono::time_point_cast(endTimepoint) + .time_since_epoch() + - std::chrono::time_point_cast(_startTimepoint) + .time_since_epoch(); - Instrumentor::get().writeProfile({_name, highResStart, elapsedTime, std::this_thread::get_id()}); + Instrumentor::get().writeProfile( + {_name, highResStart, elapsedTime, std::this_thread::get_id()} + ); _stopped = true; } private: - const char* _name; + char const* _name; std::chrono::time_point _startTimepoint; - bool _stopped {false}; + bool _stopped{false}; }; } // namespace moci #define MOCI_PROFILE 1 #if MOCI_PROFILE -#define MOCI_PROFILE_BEGIN_SESSION(name, filepath) ::moci::Instrumentor::get().beginSession(name, filepath) -#define MOCI_PROFILE_END_SESSION() ::moci::Instrumentor::get().endSession() -#define MOCI_PROFILE_SCOPE(name) ::moci::InstrumentationTimer MOCI_ANONYMOUS_VARIABLE(timer)(name); -#define MOCI_PROFILE_FUNCTION() MOCI_PROFILE_SCOPE(MOCI_FUNC_SIG) + #define MOCI_PROFILE_BEGIN_SESSION(name, filepath) \ + ::moci::Instrumentor::get().beginSession(name, filepath) + #define MOCI_PROFILE_END_SESSION() ::moci::Instrumentor::get().endSession() + #define MOCI_PROFILE_SCOPE(name) \ + ::moci::InstrumentationTimer MOCI_ANONYMOUS_VARIABLE(timer)(name); + #define MOCI_PROFILE_FUNCTION() MOCI_PROFILE_SCOPE(MOCI_FUNC_SIG) #else -#define MOCI_PROFILE_BEGIN_SESSION(name, filepath) -#define MOCI_PROFILE_END_SESSION() -#define MOCI_PROFILE_SCOPE(name) -#define MOCI_PROFILE_FUNCTION() + #define MOCI_PROFILE_BEGIN_SESSION(name, filepath) + #define MOCI_PROFILE_END_SESSION() + #define MOCI_PROFILE_SCOPE(name) + #define MOCI_PROFILE_FUNCTION() #endif diff --git a/src/moci/core/geometry/line.hpp b/src/moci/core/geometry/line.hpp index 1e77301..aff1fa6 100644 --- a/src/moci/core/geometry/line.hpp +++ b/src/moci/core/geometry/line.hpp @@ -7,8 +7,7 @@ #include -namespace moci -{ +namespace moci { template /** * @todo Write summary for class. @@ -19,12 +18,13 @@ class Line /** * @brief Construct empty line. Start and end at (0,0) */ - explicit constexpr Line() noexcept : _start({0, 0}), _end({0, 0}) { } + explicit constexpr Line() noexcept : _start({0, 0}), _end({0, 0}) {} /** * @brief Construct line from two points. */ - constexpr Line(Point start, Point end) noexcept : _start(start), _end(end) { } + constexpr Line(Point start, Point end) noexcept : _start(start), _end(end) + {} /** * @brief Returns true if start & end are equal. @@ -49,11 +49,12 @@ class Line */ [[nodiscard]] constexpr auto getSlope() const noexcept -> std::optional { - if (!isEmpty()) - { + if (!isEmpty()) { auto const x = _end.getX() - _start.getX(); auto const y = _end.getY() - _start.getY(); - if (x == Type(0)) { return std::nullopt; } + if (x == Type(0)) { + return std::nullopt; + } return (y / x); } return std::nullopt; @@ -68,7 +69,7 @@ class Line { auto const x = (_start.getX() + _end.getX()) / 2.0F; auto const y = (_start.getY() + _end.getY()) / 2.0F; - return Point {x, y}; + return Point{x, y}; } /** @@ -76,7 +77,8 @@ class Line */ [[nodiscard]] auto getAngleRadians() const noexcept -> Type { - auto const angle = std::atan2(_end.getY() - _start.getY(), _end.getX() - _start.getX()); + auto const angle + = std::atan2(_end.getY() - _start.getY(), _end.getX() - _start.getX()); return static_cast(angle); } @@ -91,7 +93,8 @@ class Line /** * @brief Returns the length of the line. * - * @details The distance between \f$(x_1,y_1)\f$ and \f$(x_2,y_2)\f$ is \f$\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\f$. + * @details The distance between \f$(x_1,y_1)\f$ and \f$(x_2,y_2)\f$ is + * \f$\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\f$. */ [[nodiscard]] auto getLength() const noexcept -> Type { @@ -109,13 +112,26 @@ class Line auto const b = _start.getX() - _end.getX(); auto const c = a * (_start.getX()) + b * (_start.getY()); - if (b < 0) { fmt::print("The line passing through points P and Q is: {0}x {1}y = {2}\n", a, b, c); } - else { fmt::print("The line passing through points P and Q is: {0}x + {1}y = {2}\n", a, b, c); } + if (b < 0) { + fmt::print( + "The line passing through points P and Q is: {0}x {1}y = {2}\n", + a, + b, + c + ); + } else { + fmt::print( + "The line passing through points P and Q is: {0}x + {1}y = {2}\n", + a, + b, + c + ); + } } private: - Point _start {}; - Point _end {}; + Point _start{}; + Point _end{}; }; template diff --git a/src/moci/core/geometry/line.test.cpp b/src/moci/core/geometry/line.test.cpp index bcfc795..8bce111 100644 --- a/src/moci/core/geometry/line.test.cpp +++ b/src/moci/core/geometry/line.test.cpp @@ -74,52 +74,73 @@ TEST_CASE("math/geometry: LineGetSlope", "[geometry]") TEST_CASE("math/geometry: LineGetAngleRadians", "[geometry]") { - constexpr auto l1 = moci::Line {}; + constexpr auto l1 = moci::Line{}; REQUIRE(l1.getAngleRadians() == 0); - constexpr auto l2 = moci::Line {{0.0F, 0.0F}, {1.0F, 1.0F}}; + constexpr auto l2 = moci::Line{ + {0.0F, 0.0F}, + {1.0F, 1.0F} + }; REQUIRE(l2.getAngleRadians() == Catch::Approx(0.7854F)); - constexpr auto l3 = moci::Line {{0.0F, 0.0F}, {1.0F, -1.0F}}; + constexpr auto l3 = moci::Line{ + {0.0F, 0.0F }, + {1.0F, -1.0F} + }; REQUIRE(l3.getAngleRadians() == Catch::Approx(-0.7854F)); } TEST_CASE("math/geometry: LineGetAngleDegrees", "[geometry]") { - constexpr auto l1 = moci::Line {}; + constexpr auto l1 = moci::Line{}; REQUIRE(l1.getAngleDegrees() == 0); - constexpr auto l2 = moci::Line {{0.0F, 0.0F}, {1.0F, 1.0F}}; + constexpr auto l2 = moci::Line{ + {0.0F, 0.0F}, + {1.0F, 1.0F} + }; REQUIRE(l2.getAngleDegrees() == Catch::Approx(45.0F)); - constexpr auto l3 = moci::Line {{0.0F, 0.0F}, {1.0F, -1.0F}}; + constexpr auto l3 = moci::Line{ + {0.0F, 0.0F }, + {1.0F, -1.0F} + }; REQUIRE(l3.getAngleDegrees() == Catch::Approx(-45.0F)); } TEST_CASE("math/geometry: LineGetLength", "[geometry]") { - constexpr auto l1 = moci::Line {}; + constexpr auto l1 = moci::Line{}; REQUIRE(l1.getLength() == 0); - constexpr auto l2 = moci::Line {{0.0F, 0.0F}, {1.0F, 0.0F}}; + constexpr auto l2 = moci::Line{ + {0.0F, 0.0F}, + {1.0F, 0.0F} + }; REQUIRE(l2.getLength() == Catch::Approx(1.0F)); - constexpr auto l3 = moci::Line {{0.0F, 0.0F}, {0.0F, -1.0F}}; + constexpr auto l3 = moci::Line{ + {0.0F, 0.0F }, + {0.0F, -1.0F} + }; REQUIRE(l3.getLength() == Catch::Approx(1.0F)); - constexpr auto l4 = moci::Line {{0.0F, 0.0F}, {10.0F, 0.0F}}; + constexpr auto l4 = moci::Line{ + {0.0F, 0.0F}, + {10.0F, 0.0F} + }; REQUIRE(l4.getLength() == Catch::Approx(10.0F)); } TEST_CASE("math/geometry: LineOperatorEqual", "[geometry]") { { - constexpr auto l1 = moci::Line {}; - constexpr auto l2 = moci::Line {}; + constexpr auto l1 = moci::Line{}; + constexpr auto l2 = moci::Line{}; REQUIRE(l1 == l2); } { - constexpr auto l1 = moci::Line {}; + constexpr auto l1 = moci::Line{}; constexpr auto l2 = moci::Line({1, 2}, {1, 1}); REQUIRE((l1 == l2) == false); } @@ -128,12 +149,12 @@ TEST_CASE("math/geometry: LineOperatorEqual", "[geometry]") TEST_CASE("math/geometry: LineOperatorNotEqual", "[geometry]") { { - constexpr auto l1 = moci::Line {}; - constexpr auto l2 = moci::Line {}; + constexpr auto l1 = moci::Line{}; + constexpr auto l2 = moci::Line{}; REQUIRE((l1 != l2) == false); } { - constexpr auto l1 = moci::Line {}; + constexpr auto l1 = moci::Line{}; constexpr auto l2 = moci::Line({1, 2}, {1, 1}); REQUIRE(l1 != l2); } diff --git a/src/moci/core/geometry/point.hpp b/src/moci/core/geometry/point.hpp index 06986e2..8ae0a22 100644 --- a/src/moci/core/geometry/point.hpp +++ b/src/moci/core/geometry/point.hpp @@ -1,13 +1,13 @@ #pragma once -namespace moci -{ +namespace moci { template class Point { public: - explicit constexpr Point() noexcept : _x(Type(0)), _y(Type(0)) { } - constexpr Point(Type x, Type y) noexcept : _x(x), _y(y) { } + explicit constexpr Point() noexcept : _x(Type(0)), _y(Type(0)) {} + + constexpr Point(Type x, Type y) noexcept : _x(x), _y(y) {} ~Point() = default; @@ -17,12 +17,17 @@ class Point Point(Point&&) noexcept = default; auto operator=(Point&&) noexcept -> Point& = default; - [[nodiscard]] constexpr auto isOrigin() const noexcept -> bool { return _x == Type(0) && _y == Type(0); } + [[nodiscard]] constexpr auto isOrigin() const noexcept -> bool + { + return _x == Type(0) && _y == Type(0); + } [[nodiscard]] constexpr auto getX() const noexcept -> Type { return _x; } + [[nodiscard]] constexpr auto getY() const noexcept -> Type { return _y; } auto setX(Type x) noexcept -> void { _x = x; } + auto setY(Type y) noexcept -> void { _y = y; } private: diff --git a/src/moci/core/geometry/rectangle.hpp b/src/moci/core/geometry/rectangle.hpp index 3150895..9e33571 100644 --- a/src/moci/core/geometry/rectangle.hpp +++ b/src/moci/core/geometry/rectangle.hpp @@ -2,8 +2,7 @@ #include -namespace moci -{ +namespace moci { template class Rectangle { @@ -11,23 +10,29 @@ class Rectangle /** * @brief Default construct. Top left at (0,0), no size. */ - explicit constexpr Rectangle() noexcept : _position(Type(0), Type(0)), _width(Type(0)), _height(Type(0)) { } + explicit constexpr Rectangle() noexcept + : _position(Type(0), Type(0)) + , _width(Type(0)) + , _height(Type(0)) + {} /** * @brief Construct at (x, y), with width & height. */ constexpr Rectangle(Type x, Type y, Type width, Type height) noexcept - : _position(x, y), _width(width), _height(height) - { - } + : _position(x, y) + , _width(width) + , _height(height) + {} /** * @brief Construct at position, with width & height. */ constexpr Rectangle(Point position, Type width, Type height) noexcept - : _position(position), _width(width), _height(height) - { - } + : _position(position) + , _width(width) + , _height(height) + {} /** * @brief Default copy construct. @@ -42,7 +47,10 @@ class Rectangle /** * @brief Returns true if the rectangle has no width & no height. */ - [[nodiscard]] constexpr auto isEmpty() const noexcept -> bool { return _width <= Type(0) && _height <= Type(0); } + [[nodiscard]] constexpr auto isEmpty() const noexcept -> bool + { + return _width <= Type(0) && _height <= Type(0); + } /** * @brief Set Top left to (x, y). @@ -97,21 +105,29 @@ class Rectangle /** * @brief Returns the x coordinate of the rectangle's right-side. */ - [[nodiscard]] constexpr auto getRight() const noexcept -> Type { return _position.getX() + _width; } + [[nodiscard]] constexpr auto getRight() const noexcept -> Type + { + return _position.getX() + _width; + } /** * @brief Returns the y coordinate of the rectangle's bottom edge. */ - [[nodiscard]] constexpr auto getBottom() const noexcept -> Type { return _position.getY() + _height; } + [[nodiscard]] constexpr auto getBottom() const noexcept -> Type + { + return _position.getY() + _height; + } /** * @brief Returns the aspect ratio width / height. */ [[nodiscard]] constexpr auto getAspectRatio() const noexcept -> Type { - if (getWidth() != Type {}) { return getWidth() / getHeight(); } + if (getWidth() != Type{}) { + return getWidth() / getHeight(); + } - return Type {}; + return Type{}; } /** @@ -122,7 +138,7 @@ class Rectangle auto const oldY = getY(); setY(oldY + amount); setHeight(getHeight() - amount); - return Rectangle {getX(), oldY, getWidth(), amount}; + return Rectangle{getX(), oldY, getWidth(), amount}; } /** @@ -133,7 +149,7 @@ class Rectangle auto const oldHeight = getHeight(); auto const newY = getY() + oldHeight - amount; setHeight(oldHeight - amount); - return Rectangle {getX(), newY, getWidth(), amount}; + return Rectangle{getX(), newY, getWidth(), amount}; } /** @@ -144,7 +160,7 @@ class Rectangle auto const oldX = getX(); setWidth(getWidth() - amount); setX(oldX + amount); - return Rectangle {oldX, getY(), amount, getHeight()}; + return Rectangle{oldX, getY(), amount, getHeight()}; } /** @@ -154,7 +170,7 @@ class Rectangle { auto const oldWidth = getWidth(); setWidth(oldWidth - amount); - return Rectangle {getX() + oldWidth - amount, getY(), amount, getHeight()}; + return Rectangle{getX() + oldWidth - amount, getY(), amount, getHeight()}; } /** @@ -164,7 +180,7 @@ class Rectangle */ [[nodiscard]] auto reduced(Type deltaX, Type deltaY) const noexcept -> Rectangle { - return Rectangle { + return Rectangle{ getX() + deltaX, // getY() + deltaY, // getWidth() - deltaX * 2, // @@ -177,7 +193,10 @@ class Rectangle * Effectively, the rectangle returned is: * (x + delta, y + delta, w - delta * 2, h - delta * 2). */ - [[nodiscard]] auto reduced(Type delta) const noexcept -> Rectangle { return reduced(delta, delta); } + [[nodiscard]] auto reduced(Type delta) const noexcept -> Rectangle + { + return reduced(delta, delta); + } /** * @brief Converts the rectangle to a rectangle based on the given type. diff --git a/src/moci/core/geometry/rectangle.test.cpp b/src/moci/core/geometry/rectangle.test.cpp index 811bfb8..17a21fc 100644 --- a/src/moci/core/geometry/rectangle.test.cpp +++ b/src/moci/core/geometry/rectangle.test.cpp @@ -9,7 +9,7 @@ TEST_CASE("math/geometry: RectangleConstructionEmpty", "[geometry]") { - moci::Rectangle r {}; + moci::Rectangle r{}; REQUIRE(r.isEmpty() == true); REQUIRE(r.getX() == 0.0F); REQUIRE(r.getY() == 0.0F); @@ -47,7 +47,7 @@ TEST_CASE("math/geometry: RectangleCopyAssignment", "[geometry]") TEST_CASE("math/geometry: RectangleSetPositionXY", "[geometry]") { - auto r = moci::Rectangle {}; + auto r = moci::Rectangle{}; r.setPosition(20, 10); REQUIRE(r.getX() == 20); REQUIRE(r.getY() == 10); @@ -55,7 +55,7 @@ TEST_CASE("math/geometry: RectangleSetPositionXY", "[geometry]") TEST_CASE("math/geometry: RectangleSetPositionPoint", "[geometry]") { - auto r = moci::Rectangle {}; + auto r = moci::Rectangle{}; r.setPosition(moci::Point(10, 5)); REQUIRE(r.getX() == 10); REQUIRE(r.getY() == 5); @@ -63,7 +63,7 @@ TEST_CASE("math/geometry: RectangleSetPositionPoint", "[geometry]") TEST_CASE("math/geometry: RectangleSetWidth", "[geometry]") { - auto r = moci::Rectangle {}; + auto r = moci::Rectangle{}; REQUIRE(r.isEmpty() == true); r.setWidth(20.0); REQUIRE(r.isEmpty() == false); @@ -72,7 +72,7 @@ TEST_CASE("math/geometry: RectangleSetWidth", "[geometry]") TEST_CASE("math/geometry: RectangleSetHeight", "[geometry]") { - auto r = moci::Rectangle {}; + auto r = moci::Rectangle{}; REQUIRE(r.isEmpty() == true); r.setHeight(20.0); REQUIRE(r.isEmpty() == false); @@ -92,31 +92,31 @@ TEST_CASE("math/geometry: RectangleSetXY", "[geometry]") TEST_CASE("math/geometry: RectangleGetRight", "[geometry]") { - auto empty = moci::Rectangle {}; + auto empty = moci::Rectangle{}; REQUIRE(empty.getRight() == 0); - auto square = moci::Rectangle {0, 0, 100, 100}; + auto square = moci::Rectangle{0, 0, 100, 100}; REQUIRE(square.getRight() == 100); } TEST_CASE("math/geometry: RectangleGetBottom", "[geometry]") { - auto empty = moci::Rectangle {}; + auto empty = moci::Rectangle{}; REQUIRE(empty.getBottom() == 0); - auto square = moci::Rectangle {0, 0, 100, 100}; + auto square = moci::Rectangle{0, 0, 100, 100}; REQUIRE(square.getBottom() == 100); } TEST_CASE("math/geometry: RectangleGetAspectRatio", "[geometry]") { - auto empty = moci::Rectangle {}; + auto empty = moci::Rectangle{}; REQUIRE(empty.getAspectRatio() == 0); - auto square = moci::Rectangle {0, 0, 100, 100}; + auto square = moci::Rectangle{0, 0, 100, 100}; REQUIRE(square.getAspectRatio() == 1); - auto display = moci::Rectangle {0.0F, 0.0F, 1920.0F, 1080.0F}; + auto display = moci::Rectangle{0.0F, 0.0F, 1920.0F, 1080.0F}; REQUIRE(display.getAspectRatio() == Catch::Approx(16.0F / 9.0F)); } @@ -244,12 +244,12 @@ TEST_CASE("math/geometry: RectangleToFloat", "[geometry]") TEST_CASE("math/geometry: RectangleOperatorEqual", "[geometry]") { { - constexpr auto r1 = moci::Rectangle {}; - constexpr auto r2 = moci::Rectangle {}; + constexpr auto r1 = moci::Rectangle{}; + constexpr auto r2 = moci::Rectangle{}; REQUIRE(r1 == r2); } { - constexpr auto r1 = moci::Rectangle {}; + constexpr auto r1 = moci::Rectangle{}; constexpr auto r2 = moci::Rectangle({1, 2}, 1, 1); REQUIRE((r1 == r2) == false); } @@ -258,12 +258,12 @@ TEST_CASE("math/geometry: RectangleOperatorEqual", "[geometry]") TEST_CASE("math/geometry: RectangleOperatorNotEqual", "[geometry]") { { - constexpr auto r1 = moci::Rectangle {}; - constexpr auto r2 = moci::Rectangle {}; + constexpr auto r1 = moci::Rectangle{}; + constexpr auto r2 = moci::Rectangle{}; REQUIRE((r1 != r2) == false); } { - constexpr auto r1 = moci::Rectangle {}; + constexpr auto r1 = moci::Rectangle{}; constexpr auto r2 = moci::Rectangle({1, 2}, 1, 1); REQUIRE(r1 != r2); } diff --git a/src/moci/core/logging.cpp b/src/moci/core/logging.cpp index 4a7c714..5fadbca 100644 --- a/src/moci/core/logging.cpp +++ b/src/moci/core/logging.cpp @@ -5,17 +5,18 @@ #include -namespace moci -{ +namespace moci { std::shared_ptr Log::sCoreLogger; std::shared_ptr Log::sClientLogger; void Log::init() { - std::vector logSinks {}; + std::vector logSinks{}; logSinks.emplace_back(std::make_shared()); - logSinks.emplace_back(std::make_shared("moci.log", true)); + logSinks.emplace_back( + std::make_shared("moci.log", true) + ); logSinks[0]->set_pattern("%^[%T] %n: %v%$"); logSinks[1]->set_pattern("[%T] [%l] %n: %v"); diff --git a/src/moci/core/logging.hpp b/src/moci/core/logging.hpp index 0032ad2..ccf94b2 100644 --- a/src/moci/core/logging.hpp +++ b/src/moci/core/logging.hpp @@ -7,16 +7,22 @@ #include -namespace moci -{ +namespace moci { class Log { public: static void init(); - inline static auto getCoreLogger() -> std::shared_ptr& { return sCoreLogger; } - inline static auto getClientLogger() -> std::shared_ptr& { return sClientLogger; } + inline static auto getCoreLogger() -> std::shared_ptr& + { + return sCoreLogger; + } + + inline static auto getClientLogger() -> std::shared_ptr& + { + return sClientLogger; + } private: static std::shared_ptr sCoreLogger; @@ -26,15 +32,15 @@ class Log } // namespace moci // Core log macros -#define MOCI_CORE_TRACE(...) ::moci::Log::getCoreLogger()->trace(__VA_ARGS__) -#define MOCI_CORE_INFO(...) ::moci::Log::getCoreLogger()->info(__VA_ARGS__) -#define MOCI_CORE_WARN(...) ::moci::Log::getCoreLogger()->warn(__VA_ARGS__) -#define MOCI_CORE_ERROR(...) ::moci::Log::getCoreLogger()->error(__VA_ARGS__) +#define MOCI_CORE_TRACE(...) ::moci::Log::getCoreLogger()->trace(__VA_ARGS__) +#define MOCI_CORE_INFO(...) ::moci::Log::getCoreLogger()->info(__VA_ARGS__) +#define MOCI_CORE_WARN(...) ::moci::Log::getCoreLogger()->warn(__VA_ARGS__) +#define MOCI_CORE_ERROR(...) ::moci::Log::getCoreLogger()->error(__VA_ARGS__) #define MOCI_CORE_CRITICAL(...) ::moci::Log::getCoreLogger()->critical(__VA_ARGS__) // Client log macros -#define MOCI_TRACE(...) ::moci::Log::getClientLogger()->trace(__VA_ARGS__) -#define MOCI_INFO(...) ::moci::Log::getClientLogger()->info(__VA_ARGS__) -#define MOCI_WARN(...) ::moci::Log::getClientLogger()->warn(__VA_ARGS__) -#define MOCI_ERROR(...) ::moci::Log::getClientLogger()->error(__VA_ARGS__) +#define MOCI_TRACE(...) ::moci::Log::getClientLogger()->trace(__VA_ARGS__) +#define MOCI_INFO(...) ::moci::Log::getClientLogger()->info(__VA_ARGS__) +#define MOCI_WARN(...) ::moci::Log::getClientLogger()->warn(__VA_ARGS__) +#define MOCI_ERROR(...) ::moci::Log::getClientLogger()->error(__VA_ARGS__) #define MOCI_CRITICAL(...) ::moci::Log::getClientLogger()->critical(__VA_ARGS__) diff --git a/src/moci/core/network/datagram.cpp b/src/moci/core/network/datagram.cpp index c7a68ab..edfe000 100644 --- a/src/moci/core/network/datagram.cpp +++ b/src/moci/core/network/datagram.cpp @@ -5,20 +5,26 @@ #include #if defined(MOCI_MAC) || defined(MOCI_LINUX) -#include + #include #elif defined(MOCI_WINDOWS) -#include + #include #endif -namespace moci -{ +namespace moci { DatagramSocket::DatagramSocket() { _pimpl = std::make_unique(); } DatagramSocket::~DatagramSocket() { _pimpl.reset(nullptr); } -auto DatagramSocket::bind(const std::string& ip, int port) -> bool { return _pimpl->bind(ip, port); } +auto DatagramSocket::bind(std::string const& ip, int port) -> bool +{ + return _pimpl->bind(ip, port); +} -auto DatagramSocket::write(std::string const& host, int port, std::span buffer) -> bool +auto DatagramSocket::write( + std::string const& host, + int port, + std::span buffer +) -> bool { return _pimpl->write(host, port, buffer); } @@ -28,7 +34,12 @@ auto DatagramSocket::write(std::string const& host, int port, Buffer const& buff return _pimpl->write(host, port, buffer); } -auto DatagramSocket::write(std::string const& host, int port, std::uint8_t const* buffer, size_t numBytes) -> bool +auto DatagramSocket::write( + std::string const& host, + int port, + std::uint8_t const* buffer, + size_t numBytes +) -> bool { return _pimpl->write(host, port, buffer, numBytes); } @@ -37,7 +48,9 @@ void DatagramSocket::listen() { _pimpl->listen(); } void DatagramSocket::shutdown() { _pimpl->shutdown(); } -void DatagramSocket::setMessageCallback(const std::function& callback) +void DatagramSocket::setMessageCallback( + std::function const& callback +) { _pimpl->setMessageCallback(callback); } diff --git a/src/moci/core/network/datagram.hpp b/src/moci/core/network/datagram.hpp index dca5e65..c23241a 100644 --- a/src/moci/core/network/datagram.hpp +++ b/src/moci/core/network/datagram.hpp @@ -6,8 +6,7 @@ #include #include -namespace moci -{ +namespace moci { class DatagramSocket { public: @@ -16,17 +15,19 @@ class DatagramSocket DatagramSocket(); ~DatagramSocket(); - auto bind(const std::string& ip, int port) -> bool; + auto bind(std::string const& ip, int port) -> bool; auto write(std::string const& host, int port, std::span buffer) -> bool; auto write(std::string const& host, int port, Buffer const& buffer) -> bool; - auto write(std::string const& host, int port, std::uint8_t const* buffer, size_t numBytes) -> bool; + auto + write(std::string const& host, int port, std::uint8_t const* buffer, size_t numBytes) + -> bool; void listen(); void shutdown(); - void setMessageCallback(const std::function& callback); + void setMessageCallback(std::function const& callback); private: class Pimpl; diff --git a/src/moci/core/network/datagram.test.cpp b/src/moci/core/network/datagram.test.cpp index 20d24c6..ce4730b 100644 --- a/src/moci/core/network/datagram.test.cpp +++ b/src/moci/core/network/datagram.test.cpp @@ -11,7 +11,7 @@ TEST_CASE("network: UDPBindToPort", "[network]") { - moci::DatagramSocket udp {}; + moci::DatagramSocket udp{}; REQUIRE(udp.bind("", 0) == true); } diff --git a/src/moci/core/network/unix/datagram.cpp b/src/moci/core/network/unix/datagram.cpp index 8410b62..3fe4fd5 100644 --- a/src/moci/core/network/unix/datagram.cpp +++ b/src/moci/core/network/unix/datagram.cpp @@ -2,66 +2,97 @@ #if defined(MOCI_LINUX) || defined(MOCI_MAC) -#include + #include -#include -#include -#include -#include + #include + #include + #include + #include -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include -namespace moci -{ +namespace moci { DatagramSocket::Pimpl::~Pimpl() { shutdown(); close(_socketDescriptor); } -auto DatagramSocket::Pimpl::write(std::string const& host, int port, std::span buffer) -> bool +auto DatagramSocket::Pimpl::write( + std::string const& host, + int port, + std::span buffer +) -> bool { return write(host, port, buffer.data(), buffer.size()); } -auto DatagramSocket::Pimpl::write(std::string const& host, int port, DatagramSocket::Buffer const& buffer) -> bool +auto DatagramSocket::Pimpl::write( + std::string const& host, + int port, + DatagramSocket::Buffer const& buffer +) -> bool { - return write(host, port, static_cast(buffer.data()), buffer.size()); + return write( + host, + port, + static_cast(buffer.data()), + buffer.size() + ); } -auto DatagramSocket::Pimpl::write(std::string const& host, int port, std::uint8_t const* const buffer, size_t numBytes) - -> bool +auto DatagramSocket::Pimpl::write( + std::string const& host, + int port, + std::uint8_t const* const buffer, + size_t numBytes +) -> bool { // Creating socket file descriptor int sockDescriptor = 0; - if ((sockDescriptor = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { return false; } + if ((sockDescriptor = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + return false; + } // Client - sockaddr_in client {}; + sockaddr_in client{}; memset(&client, 0, sizeof(client)); client.sin_family = AF_INET; client.sin_port = htons(static_cast(port)); - if (inet_aton(host.c_str(), &client.sin_addr) == 0) { return false; } - - auto const bytesSend - = sendto(sockDescriptor, buffer, numBytes, 0, reinterpret_cast(&client), sizeof(client)); - - if (bytesSend == -1) { return false; } + if (inet_aton(host.c_str(), &client.sin_addr) == 0) { + return false; + } + + auto const bytesSend = sendto( + sockDescriptor, + buffer, + numBytes, + 0, + reinterpret_cast(&client), + sizeof(client) + ); + + if (bytesSend == -1) { + return false; + } close(sockDescriptor); return true; } -auto DatagramSocket::Pimpl::bind(const std::string& ip, int port) -> bool + +auto DatagramSocket::Pimpl::bind(std::string const& ip, int port) -> bool { moci::ignoreUnused(ip); // Creating socket file descriptor - if ((_socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { return false; } + if ((_socketDescriptor = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + return false; + } - sockaddr_in servaddr {}; + sockaddr_in servaddr{}; std::memset(&servaddr, 0, sizeof(servaddr)); // Filling server information @@ -69,47 +100,58 @@ auto DatagramSocket::Pimpl::bind(const std::string& ip, int port) -> bool servaddr.sin_addr.s_addr = INADDR_ANY; servaddr.sin_port = htons(port); - timeval tv {}; + timeval tv{}; tv.tv_sec = 0; tv.tv_usec = 20'000; - setsockopt(_socketDescriptor, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv); + setsockopt(_socketDescriptor, SOL_SOCKET, SO_RCVTIMEO, (char const*)&tv, sizeof tv); // Bind the socket with the server address - return ::bind(_socketDescriptor, reinterpret_cast(&servaddr), sizeof(servaddr)) >= 0; + return ::bind( + _socketDescriptor, + reinterpret_cast(&servaddr), + sizeof(servaddr) + ) + >= 0; } void DatagramSocket::Pimpl::listen() { - _listenerThread = std::thread( - [&]() - { - sockaddr_in cliaddr {}; - std::memset(&cliaddr, 0, sizeof(cliaddr)); - - auto const maxMsgSize = 1024; - _buffer.resize(1024); - - MOCI_CORE_INFO("Start udp listen"); - _isRunning.store(true); - while (_isRunning.load()) - { - unsigned int len = 0; - auto const numBytesRecv = recvfrom(_socketDescriptor, _buffer.data(), maxMsgSize, MSG_WAITALL, - reinterpret_cast(&cliaddr), &len); - - if (numBytesRecv > 0) - { - if (_messageCallback) { _messageCallback(_buffer, _buffer.size()); } + _listenerThread = std::thread([&]() { + sockaddr_in cliaddr{}; + std::memset(&cliaddr, 0, sizeof(cliaddr)); + + auto const maxMsgSize = 1024; + _buffer.resize(1024); + + MOCI_CORE_INFO("Start udp listen"); + _isRunning.store(true); + while (_isRunning.load()) { + unsigned int len = 0; + auto const numBytesRecv = recvfrom( + _socketDescriptor, + _buffer.data(), + maxMsgSize, + MSG_WAITALL, + reinterpret_cast(&cliaddr), + &len + ); + + if (numBytesRecv > 0) { + if (_messageCallback) { + _messageCallback(_buffer, _buffer.size()); } } - }); + } + }); } void DatagramSocket::Pimpl::shutdown() { MOCI_CORE_INFO("Stop udp listen"); _isRunning.store(false); - if (_listenerThread.joinable()) { _listenerThread.join(); } + if (_listenerThread.joinable()) { + _listenerThread.join(); + } } } // namespace moci @@ -131,7 +173,8 @@ void DatagramSocket::Pimpl::shutdown() // * \param[in] max_size The size of the \p msg buffer in bytes. // * \param[in] max_wait_ms The maximum number of milliseconds to wait for a message. // * -// * \return -1 if an error occurs or the function timed out, the number of bytes received otherwise. +// * \return -1 if an error occurs or the function timed out, the number of bytes received +// otherwise. // */ // int udp_server::timed_recv(char *msg, size_t max_size, int max_wait_ms) // { @@ -153,9 +196,9 @@ void DatagramSocket::Pimpl::shutdown() // return ::recv(f_socket, msg, max_size, 0); // } -// // our socket has no data -// errno = EAGAIN; -// return -1; +// // our socket has no data +// errno = EAGAIN; +// return -1; // } #endif diff --git a/src/moci/core/network/unix/datagram.hpp b/src/moci/core/network/unix/datagram.hpp index e026bc9..49ba7f0 100644 --- a/src/moci/core/network/unix/datagram.hpp +++ b/src/moci/core/network/unix/datagram.hpp @@ -4,18 +4,17 @@ #if defined(MOCI_LINUX) || defined(MOCI_MAC) -#include + #include -#include + #include -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include -namespace moci -{ +namespace moci { class DatagramSocket::Pimpl { @@ -23,25 +22,31 @@ class DatagramSocket::Pimpl Pimpl() = default; ~Pimpl(); - auto bind(const std::string& ip, int port) -> bool; + auto bind(std::string const& ip, int port) -> bool; - static auto write(std::string const& host, int port, std::span buffer) -> bool; - static auto write(std::string const& host, int port, DatagramSocket::Buffer const& buffer) -> bool; - static auto write(std::string const& host, int port, std::uint8_t const* buffer, size_t numBytes) -> bool; + static auto write(std::string const& host, int port, std::span buffer) + -> bool; + static auto + write(std::string const& host, int port, DatagramSocket::Buffer const& buffer) -> bool; + static auto + write(std::string const& host, int port, std::uint8_t const* buffer, size_t numBytes) + -> bool; void listen(); void shutdown(); - void setMessageCallback(const std::function& callback) + void setMessageCallback( + std::function const& callback + ) { _messageCallback = callback; } private: - std::atomic _isRunning {false}; - int _socketDescriptor {}; - DatagramSocket::Buffer _buffer {}; + std::atomic _isRunning{false}; + int _socketDescriptor{}; + DatagramSocket::Buffer _buffer{}; std::thread _listenerThread; std::function _messageCallback = nullptr; }; diff --git a/src/moci/core/network/windows/datagram.cpp b/src/moci/core/network/windows/datagram.cpp index 6716e4d..0240a23 100644 --- a/src/moci/core/network/windows/datagram.cpp +++ b/src/moci/core/network/windows/datagram.cpp @@ -2,37 +2,49 @@ #if defined(MOCI_WINDOWS) -#include + #include -#include -#include -#include -#include + #include + #include + #include + #include -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif -#include -#include + #include + #include -#pragma comment(lib, "Ws2_32.lib") + #pragma comment(lib, "Ws2_32.lib") -namespace moci -{ -DatagramSocket::Pimpl::~Pimpl() { } +namespace moci { +DatagramSocket::Pimpl::~Pimpl() {} -bool DatagramSocket::Pimpl::write(std::string const& host, int port, std::span buffer) +bool DatagramSocket::Pimpl::write( + std::string const& host, + int port, + std::span buffer +) { return write(host, port, buffer.data(), buffer.size()); } -bool DatagramSocket::Pimpl::write(std::string const& host, int port, DatagramSocket::Buffer const& buffer) +bool DatagramSocket::Pimpl::write( + std::string const& host, + int port, + DatagramSocket::Buffer const& buffer +) { return write(host, port, buffer.data(), buffer.size()); } -bool DatagramSocket::Pimpl::write(std::string const& host, int port, std::uint8_t const* const buffer, size_t numBytes) +bool DatagramSocket::Pimpl::write( + std::string const& host, + int port, + std::uint8_t const* const buffer, + size_t numBytes +) { ignoreUnused(host); ignoreUnused(port); @@ -45,16 +57,14 @@ bool DatagramSocket::Pimpl::bind(std::string ip, int port) { WSADATA wsa; auto rc = WSAStartup(MAKEWORD(2, 0), &wsa); - if (rc != 0) - { + if (rc != 0) { MOCI_CORE_ERROR("Could not start winsock: {}", rc); return false; } MOCI_CORE_INFO("Winsock start"); socketDescriptor_ = socket(AF_INET, SOCK_DGRAM, 0); - if (socketDescriptor_ == INVALID_SOCKET) - { + if (socketDescriptor_ == INVALID_SOCKET) { MOCI_CORE_ERROR("Could not create udp socket: {}", WSAGetLastError()); return false; } @@ -67,8 +77,7 @@ bool DatagramSocket::Pimpl::bind(std::string ip, int port) addr.sin_addr.s_addr = ADDR_ANY; rc = ::bind(socketDescriptor_, (SOCKADDR*)&addr, sizeof(SOCKADDR_IN)); - if (rc == SOCKET_ERROR) - { + if (rc == SOCKET_ERROR) { MOCI_CORE_ERROR("Could not bind to port: {}", WSAGetLastError()); return false; } @@ -80,35 +89,42 @@ bool DatagramSocket::Pimpl::bind(std::string ip, int port) void DatagramSocket::Pimpl::listen() { - listenerThread_ = std::thread( - [&]() - { - SOCKADDR_IN remoteAddr; - int remoteAddrLen = sizeof(SOCKADDR_IN); - std::memset(&remoteAddr, 0, sizeof(remoteAddr)); - - buffer_.resize(1024); - - MOCI_CORE_INFO("Start udp listen"); - isRunning_.store(true); - while (isRunning_.load()) - { - auto const rc = recvfrom(socketDescriptor_, reinterpret_cast(buffer_.data()), - static_cast(buffer_.size()), 0, (SOCKADDR*)&remoteAddr, &remoteAddrLen); - if (rc == SOCKET_ERROR) { MOCI_CORE_ERROR("recvfrom, error code: {}", WSAGetLastError()); } - else - { - if (messageCallback_) { messageCallback_(buffer_, buffer_.size()); } + listenerThread_ = std::thread([&]() { + SOCKADDR_IN remoteAddr; + int remoteAddrLen = sizeof(SOCKADDR_IN); + std::memset(&remoteAddr, 0, sizeof(remoteAddr)); + + buffer_.resize(1024); + + MOCI_CORE_INFO("Start udp listen"); + isRunning_.store(true); + while (isRunning_.load()) { + auto const rc = recvfrom( + socketDescriptor_, + reinterpret_cast(buffer_.data()), + static_cast(buffer_.size()), + 0, + (SOCKADDR*)&remoteAddr, + &remoteAddrLen + ); + if (rc == SOCKET_ERROR) { + MOCI_CORE_ERROR("recvfrom, error code: {}", WSAGetLastError()); + } else { + if (messageCallback_) { + messageCallback_(buffer_, buffer_.size()); } } - }); + } + }); } void DatagramSocket::Pimpl::shutdown() { MOCI_CORE_INFO("Stop udp listen"); isRunning_.store(false); - if (listenerThread_.joinable()) { listenerThread_.join(); } + if (listenerThread_.joinable()) { + listenerThread_.join(); + } } } // namespace moci diff --git a/src/moci/core/network/windows/datagram.hpp b/src/moci/core/network/windows/datagram.hpp index 4d3654e..883dd55 100644 --- a/src/moci/core/network/windows/datagram.hpp +++ b/src/moci/core/network/windows/datagram.hpp @@ -4,18 +4,17 @@ #if defined(MOCI_WINDOWS) -#include + #include -#include + #include -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include -namespace moci -{ +namespace moci { class DatagramSocket::Pimpl { @@ -27,21 +26,23 @@ class DatagramSocket::Pimpl bool write(std::string const& host, int port, std::span buffer); bool write(std::string const& host, int port, DatagramSocket::Buffer const& buffer); - bool write(std::string const& host, int port, std::uint8_t const* buffer, size_t numBytes); + bool + write(std::string const& host, int port, std::uint8_t const* buffer, size_t numBytes); void listen(); void shutdown(); - void setMessageCallback(std::function callback) + void + setMessageCallback(std::function callback) { messageCallback_ = callback; } private: - std::atomic isRunning_ {false}; - unsigned long long socketDescriptor_ {}; - DatagramSocket::Buffer buffer_ {}; + std::atomic isRunning_{false}; + unsigned long long socketDescriptor_{}; + DatagramSocket::Buffer buffer_{}; std::thread listenerThread_; std::function messageCallback_ = nullptr; }; diff --git a/src/moci/core/preprocessor.hpp b/src/moci/core/preprocessor.hpp index dcf0389..859c6a1 100644 --- a/src/moci/core/preprocessor.hpp +++ b/src/moci/core/preprocessor.hpp @@ -1,194 +1,209 @@ #pragma once #if defined(_WIN32) || defined(_WIN64) -#define MOCI_WIN32 1 -#define MOCI_WINDOWS 1 + #define MOCI_WIN32 1 + #define MOCI_WINDOWS 1 #elif defined(MOCI_ANDROID) -#undef MOCI_ANDROID -#define MOCI_ANDROID 1 + #undef MOCI_ANDROID + #define MOCI_ANDROID 1 #elif defined(__FreeBSD__) || (__OpenBSD__) -#define MOCI_BSD 1 + #define MOCI_BSD 1 #elif defined(LINUX) || defined(__linux__) -#define MOCI_LINUX 1 + #define MOCI_LINUX 1 #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__) -#define CF_EXCLUDE_CSTD_HEADERS 1 -#include // (needed to find out what platform we're using) + #define CF_EXCLUDE_CSTD_HEADERS 1 + #include // (needed to find out what platform we're using) -#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR -#define MOCI_IPHONE 1 -#define MOCI_IOS 1 + #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR + #define MOCI_IPHONE 1 + #define MOCI_IOS 1 + #else + #define MOCI_MAC 1 + #endif #else -#define MOCI_MAC 1 -#endif -#else -#error "Unknown platform!" + #error "Unknown platform!" #endif #if MOCI_WINDOWS -#ifdef _MSC_VER -#ifdef _WIN64 -#define MOCI_64BIT 1 -#else -#define MOCI_32BIT 1 -#endif -#endif + #ifdef _MSC_VER + #ifdef _WIN64 + #define MOCI_64BIT 1 + #else + #define MOCI_32BIT 1 + #endif + #endif -#ifdef _DEBUG -#define MOCI_DEBUG 1 -#endif + #ifdef _DEBUG + #define MOCI_DEBUG 1 + #endif -#ifdef __MINGW32__ -#define MOCI_MINGW 1 -#ifdef __MINGW64__ -#define MOCI_64BIT 1 -#else -#define MOCI_32BIT 1 -#endif -#endif + #ifdef __MINGW32__ + #define MOCI_MINGW 1 + #ifdef __MINGW64__ + #define MOCI_64BIT 1 + #else + #define MOCI_32BIT 1 + #endif + #endif -/** If defined, this indicates that the processor is little-endian. */ -#define MOCI_LITTLE_ENDIAN 1 + /** If defined, this indicates that the processor is little-endian. */ + #define MOCI_LITTLE_ENDIAN 1 -#define MOCI_INTEL 1 + #define MOCI_INTEL 1 #endif #if MOCI_MAC || MOCI_IOS -#if defined(DEBUG) || defined(_DEBUG) || !(defined(NDEBUG) || defined(_NDEBUG)) -#define MOCI_DEBUG 1 -#endif - -#if !(defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG) || defined(_NDEBUG)) -#error \ - "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build," -#endif - -#ifdef __LITTLE_ENDIAN__ -#define MOCI_LITTLE_ENDIAN 1 -#else -#define MOCI_BIG_ENDIAN 1 -#endif - -#ifdef __LP64__ -#define MOCI_64BIT 1 -#else -#define MOCI_32BIT 1 -#endif - -#if defined(__ppc__) || defined(__ppc64__) -#error "PowerPC is no longer supported by JUCE!" -#elif defined(__arm__) || defined(__arm64__) -#define MOCI_ARM 1 -#else -#define MOCI_INTEL 1 -#endif - -#if MOCI_MAC -#if !defined(MAC_OS_X_VERSION_10_11) -#error \ - "The 10.11 SDK (Xcode 7.3.1+) is required to build JUCE apps. You can create apps that run on macOS 10.7+ by changing the deployment target." -#elif MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7 -#error "Building for OSX 10.6 is no longer supported!" -#endif -#endif + #if defined(DEBUG) || defined(_DEBUG) || !(defined(NDEBUG) || defined(_NDEBUG)) + #define MOCI_DEBUG 1 + #endif + + #if !(defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG) || defined(_NDEBUG)) + #error \ + "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build," + #endif + + #ifdef __LITTLE_ENDIAN__ + #define MOCI_LITTLE_ENDIAN 1 + #else + #define MOCI_BIG_ENDIAN 1 + #endif + + #ifdef __LP64__ + #define MOCI_64BIT 1 + #else + #define MOCI_32BIT 1 + #endif + + #if defined(__ppc__) || defined(__ppc64__) + #error "PowerPC is no longer supported by JUCE!" + #elif defined(__arm__) || defined(__arm64__) + #define MOCI_ARM 1 + #else + #define MOCI_INTEL 1 + #endif + + #if MOCI_MAC + #if !defined(MAC_OS_X_VERSION_10_11) + #error \ + "The 10.11 SDK (Xcode 7.3.1+) is required to build JUCE apps. You can create apps that run on macOS 10.7+ by changing the deployment target." + #elif MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7 + #error "Building for OSX 10.6 is no longer supported!" + #endif + #endif #endif #if MOCI_LINUX || MOCI_ANDROID -// Allow override for big-endian Linux platforms -#if defined(__LITTLE_ENDIAN__) || !defined(MOCI_BIG_ENDIAN) -#define MOCI_LITTLE_ENDIAN 1 -#undef MOCI_BIG_ENDIAN -#else -#undef MOCI_LITTLE_ENDIAN -#define MOCI_BIG_ENDIAN 1 -#endif + // Allow override for big-endian Linux platforms + #if defined(__LITTLE_ENDIAN__) || !defined(MOCI_BIG_ENDIAN) + #define MOCI_LITTLE_ENDIAN 1 + #undef MOCI_BIG_ENDIAN + #else + #undef MOCI_LITTLE_ENDIAN + #define MOCI_BIG_ENDIAN 1 + #endif -#if defined(__LP64__) || defined(_LP64) || defined(__arm64__) -#define MOCI_64BIT 1 -#else -#define MOCI_32BIT 1 -#endif + #if defined(__LP64__) || defined(_LP64) || defined(__arm64__) + #define MOCI_64BIT 1 + #else + #define MOCI_32BIT 1 + #endif -#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) -#define MOCI_ARM 1 -#elif __MMX__ || __SSE__ || __amd64__ -#define MOCI_INTEL 1 -#endif + #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__) + #define MOCI_ARM 1 + #elif __MMX__ || __SSE__ || __amd64__ + #define MOCI_INTEL 1 + #endif #endif // Compiler type macros. #if defined(__clang__) -#define MOCI_COMPILER_CLANG 1 + #define MOCI_COMPILER_CLANG 1 #elif defined(__GNUC__) -#define MOCI_COMPILER_GCC 1 + #define MOCI_COMPILER_GCC 1 #elif defined(_MSC_VER) -#define MOCI_COMPILER_MSVC 1 + #define MOCI_COMPILER_MSVC 1 #elif defined(__INTEL_COMPILER) -#define MOCI_COMPILER_INTEL 1 + #define MOCI_COMPILER_INTEL 1 #elif defined(__BORLANDC__) -#define MOCI_COMPILER_BORLAND 1 + #define MOCI_COMPILER_BORLAND 1 #elif defined(__IBMCPP__) -#define MOCI_COMPILER_IBM 1 + #define MOCI_COMPILER_IBM 1 #else -#error unknown compiler + #error unknown compiler #endif // Resolve which function signature macro will be used. Note that this only // is resolved when the (pre)compiler starts, so the syntax highlighting // could mark the wrong one in your editor! -#if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) \ - || defined(__ghs__) -#define MOCI_FUNC_SIG __PRETTY_FUNCTION__ +#if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) \ + || (defined(__ICC) && (__ICC >= 600)) || defined(__ghs__) + #define MOCI_FUNC_SIG __PRETTY_FUNCTION__ #elif defined(__DMC__) && (__DMC__ >= 0x810) -#define MOCI_FUNC_SIG __PRETTY_FUNCTION__ + #define MOCI_FUNC_SIG __PRETTY_FUNCTION__ #elif defined(__FUNCSIG__) -#define MOCI_FUNC_SIG __FUNCSIG__ -#elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) -#define MOCI_FUNC_SIG __FUNCTION__ + #define MOCI_FUNC_SIG __FUNCSIG__ +#elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) \ + || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) + #define MOCI_FUNC_SIG __FUNCTION__ #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550) -#define MOCI_FUNC_SIG __FUNC__ + #define MOCI_FUNC_SIG __FUNC__ #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) -#define MOCI_FUNC_SIG __func__ + #define MOCI_FUNC_SIG __func__ #elif defined(__cplusplus) && (__cplusplus >= 201103) -#define MOCI_FUNC_SIG __func__ + #define MOCI_FUNC_SIG __func__ #else -#define MOCI_FUNC_SIG "MOCI_FUNC_SIG unknown!" + #define MOCI_FUNC_SIG "MOCI_FUNC_SIG unknown!" #endif #define MOCI_ENABLE_ASSERTIONS 1 #ifdef MOCI_ENABLE_ASSERTIONS -#define MOCI_ASSERT(x, ...) \ - { \ - if (!(x)) { MOCI_CRITICAL("Assertion Failed: {0}:{1}: {2}", __FILE__, __LINE__, __VA_ARGS__); } \ - } -#define MOCI_CORE_ASSERT(x, ...) \ - { \ - if (!(x)) { MOCI_CORE_CRITICAL("Assertion Failed: {0}:{1}: {2}", __FILE__, __LINE__, __VA_ARGS__); } \ - } -#else -#define MOCI_ASSERT(x, ...) -#define MOCI_CORE_ASSERT(x, ...) + #define MOCI_ASSERT(x, ...) \ + { \ + if (!(x)) { \ + MOCI_CRITICAL( \ + "Assertion Failed: {0}:{1}: {2}", \ + __FILE__, \ + __LINE__, \ + __VA_ARGS__ \ + ); \ + } \ + } + #define MOCI_CORE_ASSERT(x, ...) \ + { \ + if (!(x)) { \ + MOCI_CORE_CRITICAL( \ + "Assertion Failed: {0}:{1}: {2}", \ + __FILE__, \ + __LINE__, \ + __VA_ARGS__ \ + ); \ + } \ + } +#else + #define MOCI_ASSERT(x, ...) + #define MOCI_CORE_ASSERT(x, ...) #endif #define BIT(x) (1 << x) #if defined(__has_builtin) -#define MOCI_HAS_BUILTIN(...) __has_builtin(__VA_ARGS__) + #define MOCI_HAS_BUILTIN(...) __has_builtin(__VA_ARGS__) #else -#define MOCI_HAS_BUILTIN(...) 0 + #define MOCI_HAS_BUILTIN(...) 0 #endif #if defined(__has_feature) -#define MOCI_HAS_FEATURE(...) __has_feature(__VA_ARGS__) + #define MOCI_HAS_FEATURE(...) __has_feature(__VA_ARGS__) #else -#define MOCI_HAS_FEATURE(...) 0 + #define MOCI_HAS_FEATURE(...) 0 #endif /** @@ -196,28 +211,30 @@ * str and ending with a number that varies with the line. */ #ifndef MOCI_ANONYMOUS_VARIABLE -#define MOCI_CONCATENATE_IMPL(s1, s2) s1##s2 -#define MOCI_CONCATENATE(s1, s2) MOCI_CONCATENATE_IMPL(s1, s2) -#ifdef __COUNTER__ -// Modular builds build each module with its own preprocessor state, meaning -// `__COUNTER__` no longer provides a unique number across a TU. Instead of -// calling back to just `__LINE__`, use a mix of `__COUNTER__` and `__LINE__` -// to try provide as much uniqueness as possible. -#if MOCI_HAS_FEATURE(modules) -#define MOCI_ANONYMOUS_VARIABLE(str) MOCI_CONCATENATE(MOCI_CONCATENATE(MOCI_CONCATENATE(str, __COUNTER__), _), __LINE__) -#else -#define MOCI_ANONYMOUS_VARIABLE(str) MOCI_CONCATENATE(str, __COUNTER__) -#endif -#else -#define MOCI_ANONYMOUS_VARIABLE(str) MOCI_CONCATENATE(str, __LINE__) -#endif -#endif - -namespace moci -{ + #define MOCI_CONCATENATE_IMPL(s1, s2) s1##s2 + #define MOCI_CONCATENATE(s1, s2) MOCI_CONCATENATE_IMPL(s1, s2) + #ifdef __COUNTER__ + // Modular builds build each module with its own preprocessor state, meaning + // `__COUNTER__` no longer provides a unique number across a TU. Instead of + // calling back to just `__LINE__`, use a mix of `__COUNTER__` and `__LINE__` + // to try provide as much uniqueness as possible. + #if MOCI_HAS_FEATURE(modules) + #define MOCI_ANONYMOUS_VARIABLE(str) \ + MOCI_CONCATENATE( \ + MOCI_CONCATENATE(MOCI_CONCATENATE(str, __COUNTER__), _), \ + __LINE__ \ + ) + #else + #define MOCI_ANONYMOUS_VARIABLE(str) MOCI_CONCATENATE(str, __COUNTER__) + #endif + #else + #define MOCI_ANONYMOUS_VARIABLE(str) MOCI_CONCATENATE(str, __LINE__) + #endif +#endif + +namespace moci { template auto ignoreUnused(Types&&... /*unused*/) -> void -{ -} +{} } // namespace moci diff --git a/src/moci/core/property_map.hpp b/src/moci/core/property_map.hpp index f67806e..af3bc90 100644 --- a/src/moci/core/property_map.hpp +++ b/src/moci/core/property_map.hpp @@ -7,8 +7,7 @@ #include #include -namespace moci -{ +namespace moci { /** * @brief Container that maps keys to property objects. @@ -30,7 +29,7 @@ class PropertyMap /** * @brief Constructor. Sets the name. */ - explicit PropertyMap(std::string name) : _name(std::move(name)) { } + explicit PropertyMap(std::string name) : _name(std::move(name)) {} /** * @brief Sets the name. @@ -40,20 +39,29 @@ class PropertyMap /** * @brief Returns the name. */ - [[nodiscard]] auto getName() const noexcept -> std::string_view { return std::string_view(_name); } + [[nodiscard]] auto getName() const noexcept -> std::string_view + { + return std::string_view(_name); + } /** * @brief Sets or updates the property at key. */ - auto setProperty(KeyType const& key, Property&& p) -> void { _data.insert_or_assign(key, p); } + auto setProperty(KeyType const& key, Property&& p) -> void + { + _data.insert_or_assign(key, p); + } /** * @brief Returns the property at key. */ - [[nodiscard]] auto getProperty(KeyType const& key) const noexcept -> std::optional + [[nodiscard]] auto getProperty(KeyType const& key) const noexcept + -> std::optional { auto const search = _data.find(key); - if (search != _data.end()) { return search->second; } + if (search != _data.end()) { + return search->second; + } return std::nullopt; } @@ -74,7 +82,7 @@ class PropertyMap } private: - std::string _name {}; - std::unordered_map _data {}; + std::string _name{}; + std::unordered_map _data{}; }; } // namespace moci diff --git a/src/moci/core/scope_guard.hpp b/src/moci/core/scope_guard.hpp index 2045b7f..cbcaa1f 100644 --- a/src/moci/core/scope_guard.hpp +++ b/src/moci/core/scope_guard.hpp @@ -1,63 +1,74 @@ #pragma once #include -namespace moci -{ + +namespace moci { template class ScopeGuard { - bool _committed {false}; + bool _committed{false}; Lambda _rollbackLambda; public: - explicit ScopeGuard(const Lambda& l) : _rollbackLambda(l) { } + explicit ScopeGuard(Lambda const& l) : _rollbackLambda(l) {} - ScopeGuard(const ScopeGuard& sc) : _rollbackLambda(sc._rollbackLambda) + ScopeGuard(ScopeGuard const& sc) : _rollbackLambda(sc._rollbackLambda) { - if (sc._committed) { _committed = true; } - else { sc.commit(); } + if (sc._committed) { + _committed = true; + } else { + sc.commit(); + } } ScopeGuard(ScopeGuard&& sc) noexcept : _rollbackLambda(sc._rollbackLambda) { - if (sc._committed) { _committed = true; } - else { sc.commit(); } + if (sc._committed) { + _committed = true; + } else { + sc.commit(); + } } - // WARNING: only safe if adquire lambda does not throw, otherwise release lambda is never invoked, because the scope - // guard never finished initialistion.. + // WARNING: only safe if adquire lambda does not throw, otherwise release lambda is + // never invoked, because the scope guard never finished initialistion.. template - ScopeGuard(const AdquireLambda& al, const Lambda& l) : _rollbackLambda(l) + ScopeGuard(AdquireLambda const& al, Lambda const& l) : _rollbackLambda(l) { std::forward(al)(); } - // WARNING: only safe if adquire lambda does not throw, otherwise release lambda is never invoked, because the scope - // guard never finished initialistion.. + // WARNING: only safe if adquire lambda does not throw, otherwise release lambda is + // never invoked, because the scope guard never finished initialistion.. template ScopeGuard(AdquireLambda&& al, L&& l) : _rollbackLambda(std::forward(l)) { - std::forward(al)(); // just in case the functor has &&-qualified operator() + std::forward(al)( + ); // just in case the functor has &&-qualified operator() } ~ScopeGuard() { - if (!_committed) { _rollbackLambda(); } + if (!_committed) { + _rollbackLambda(); + } } inline void commit() { _committed = true; } }; -// WARNING: only safe if adquire lambda does not throw, otherwise release lambda is never invoked, because the scope -// guard never finished initialistion.. +// WARNING: only safe if adquire lambda does not throw, otherwise release lambda is never +// invoked, because the scope guard never finished initialistion.. template -auto makeScopeGuardThatDoesNotRollbackIfAdquireThrows(aLambda&& a, rLambda&& r) -> ScopeGuard +auto makeScopeGuardThatDoesNotRollbackIfAdquireThrows(aLambda&& a, rLambda&& r) + -> ScopeGuard { return ScopeGuard(std::forward(a), std::forward(r)); } template -auto makeScopeGuardThatDoesRollbackIfAdquireThrows(aLambda&& a, rLambda&& r) -> ScopeGuard +auto makeScopeGuardThatDoesRollbackIfAdquireThrows(aLambda&& a, rLambda&& r) + -> ScopeGuard { auto scope = ScopeGuard(std::forward(r)); a(); diff --git a/src/moci/core/scope_guard.test.cpp b/src/moci/core/scope_guard.test.cpp index 383dad6..dc989fa 100644 --- a/src/moci/core/scope_guard.test.cpp +++ b/src/moci/core/scope_guard.test.cpp @@ -19,12 +19,10 @@ TEST_CASE("core: MakeScopeGuardMultiple", "[core]") { auto i = 0; auto g1 = moci::makeScopeGuard([&i]() { REQUIRE(i == 20); }); - auto g2 = moci::makeScopeGuard( - [&i]() mutable - { - REQUIRE(i == 10); - i = 20; - }); + auto g2 = moci::makeScopeGuard([&i]() mutable { + REQUIRE(i == 10); + i = 20; + }); i = 10; } @@ -33,24 +31,21 @@ TEST_CASE("core: MakeScopeGuardNoRolebackOnAquireThrowThrow", "[core]") { std::vector vec1; std::vector vec2; - try - { - auto doesNOTRollbackIfAdquireThrows = [&]() - { + try { + auto doesNOTRollbackIfAdquireThrows = [&]() { vec1.push_back(42); - auto a = moci::makeScopeGuard( - [&]() - { - REQUIRE(!vec1.empty()); - vec1.pop_back(); - }); + auto a = moci::makeScopeGuard([&]() { + REQUIRE(!vec1.empty()); + vec1.pop_back(); + }); - auto b = moci::makeScopeGuardThatDoesNotRollbackIfAdquireThrows([&]() { vec2.push_back(42); }, - [&]() - { - REQUIRE(!vec1.empty()); - vec2.pop_back(); - }); + auto b = moci::makeScopeGuardThatDoesNotRollbackIfAdquireThrows( + [&]() { vec2.push_back(42); }, + [&]() { + REQUIRE(!vec1.empty()); + vec2.pop_back(); + } + ); throw 1; // b.commit(); @@ -58,9 +53,7 @@ TEST_CASE("core: MakeScopeGuardNoRolebackOnAquireThrowThrow", "[core]") }; doesNOTRollbackIfAdquireThrows(); - } - catch (...) - { + } catch (...) { REQUIRE(vec1.empty()); REQUIRE(vec2.empty()); } @@ -70,22 +63,20 @@ TEST_CASE("core: MakeScopeGuardNoRolebackOnAquireThrowNoThrow", "[core]") { std::vector vec1; std::vector vec2; - auto doesNOTRollbackIfAdquireThrows = [&]() - { + auto doesNOTRollbackIfAdquireThrows = [&]() { vec1.push_back(42); - auto a = moci::makeScopeGuard( - [&]() - { - REQUIRE(!vec1.empty()); - vec1.pop_back(); - }); + auto a = moci::makeScopeGuard([&]() { + REQUIRE(!vec1.empty()); + vec1.pop_back(); + }); - auto b = moci::makeScopeGuardThatDoesNotRollbackIfAdquireThrows([&]() { vec2.push_back(42); }, - [&]() - { - REQUIRE(!vec1.empty()); - vec2.pop_back(); - }); + auto b = moci::makeScopeGuardThatDoesNotRollbackIfAdquireThrows( + [&]() { vec2.push_back(42); }, + [&]() { + REQUIRE(!vec1.empty()); + vec2.pop_back(); + } + ); b.commit(); a.commit(); }; @@ -99,35 +90,28 @@ TEST_CASE("core: MakeScopeGuardRolebackOnAquireThrow", "[core]") { std::vector vec1; std::vector vec2; - try - { - auto doesRollbackIfAdquireThrows = [&]() - { + try { + auto doesRollbackIfAdquireThrows = [&]() { vec1.push_back(42); - auto a = moci::makeScopeGuard( - [&]() - { - REQUIRE(!vec1.empty()); - vec1.pop_back(); - }); + auto a = moci::makeScopeGuard([&]() { + REQUIRE(!vec1.empty()); + vec1.pop_back(); + }); auto b = moci::makeScopeGuardThatDoesRollbackIfAdquireThrows( - [&]() - { - vec2.push_back(42); - throw 1; - }, - [&]() - { - REQUIRE(!vec1.empty()); - vec2.pop_back(); - }); + [&]() { + vec2.push_back(42); + throw 1; + }, + [&]() { + REQUIRE(!vec1.empty()); + vec2.pop_back(); + } + ); }; doesRollbackIfAdquireThrows(); - } - catch (...) - { + } catch (...) { REQUIRE(vec1.empty()); REQUIRE(vec2.empty()); } diff --git a/src/moci/core/strings.hpp b/src/moci/core/strings.hpp index 0538cfc..665143d 100644 --- a/src/moci/core/strings.hpp +++ b/src/moci/core/strings.hpp @@ -12,8 +12,7 @@ #include #include -namespace moci -{ +namespace moci { /** * @brief Collection of string helper functions. @@ -30,15 +29,17 @@ class Strings /** * @brief Remove all leading spaces on the given string in place. */ - static inline auto leftTrim(std::string& str) -> void + inline static auto leftTrim(std::string& str) -> void { - str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](int ch) { return std::isspace(ch) == 0; })); + str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](int ch) { + return std::isspace(ch) == 0; + })); } /** * @brief Remove all leading spaces on the given string copied. */ - static inline auto leftTrimCopy(std::string str) -> std::string + inline static auto leftTrimCopy(std::string str) -> std::string { leftTrim(str); return str; @@ -47,17 +48,22 @@ class Strings /** * @brief Remove all trailing spaces on the given string in place */ - static inline auto rightTrim(std::string& str) -> void + inline static auto rightTrim(std::string& str) -> void { str.erase( - std::find_if(str.rbegin(), str.rend(), [](int character) { return std::isspace(character) == 0; }).base(), - str.end()); + std::find_if( + str.rbegin(), + str.rend(), + [](int character) { return std::isspace(character) == 0; } + ).base(), + str.end() + ); } /** * @brief Remove all trailing spaces on the given string copied. */ - static inline auto rightTrimCopy(std::string str) -> std::string + inline static auto rightTrimCopy(std::string str) -> std::string { rightTrim(str); return str; @@ -66,7 +72,7 @@ class Strings /** * @brief Remove all leading & trailing spaces on the given string in place. */ - static inline auto trim(std::string& str) -> void + inline static auto trim(std::string& str) -> void { leftTrim(str); rightTrim(str); @@ -75,7 +81,7 @@ class Strings /** * @brief Remove all leading & trailing spaces on the given string copied. */ - static inline auto trimCopy(std::string str) -> std::string + inline static auto trimCopy(std::string str) -> std::string { trim(str); return str; @@ -84,48 +90,47 @@ class Strings /** * @brief Returns a vector of string splits. Split by the delimiter. */ - static inline auto split(std::string const& str, char delimiter) -> std::vector + inline static auto split(std::string const& str, char delimiter) + -> std::vector { std::vector tokens; std::string token; std::istringstream tokenStream(str); - while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } + while (std::getline(tokenStream, token, delimiter)) { + tokens.push_back(token); + } return tokens; } /** - * @brief Convertes a string to int. If it fails an empty optional will be returned. If yout input a string with - * numbers at the beginning followed by characters, it will giv you the number at the beginning. Even if there are - * no spaces between digits & characters. + * @brief Convertes a string to int. If it fails an empty optional will be returned. If + * yout input a string with numbers at the beginning followed by characters, it will giv + * you the number at the beginning. Even if there are no spaces between digits & + * characters. * * Strings::ToInt("-143abc") = -143 */ - static inline auto toInt(std::string const& input) -> std::optional + inline static auto toInt(std::string const& input) -> std::optional { - try - { + try { int output = std::stoi(input); return output; - } - catch (...) - { + } catch (...) { return std::nullopt; } } /** - * @brief Same as ToInt. First converted to a plain int, then static_cast into the given integer type. + * @brief Same as ToInt. First converted to a plain int, then static_cast into the given + * integer type. */ template static auto toInteger(std::string const& input) -> std::optional { - try - { + try { int output = std::stoi(input); return static_cast(output); - } - catch (...) - { + } catch (...) { return std::nullopt; } } diff --git a/src/moci/core/system/apple/info.cpp b/src/moci/core/system/apple/info.cpp index 21e5ceb..428e652 100644 --- a/src/moci/core/system/apple/info.cpp +++ b/src/moci/core/system/apple/info.cpp @@ -2,18 +2,17 @@ #if defined(MOCI_MAC) -#include + #include -#include -#include -#include + #include + #include + #include -#include -#include -#include + #include + #include + #include -namespace moci -{ +namespace moci { std::string SystemInfo::Pimpl::getOSName() { struct utsname uts; @@ -25,7 +24,9 @@ std::string SystemInfo::Pimpl::getVendor() { char buffer[512]; size_t size = sizeof(buffer); - if (sysctlbyname("machdep.cpu.vendor", &buffer, &size, nullptr, 0) < 0) { perror("sysctl"); } + if (sysctlbyname("machdep.cpu.vendor", &buffer, &size, nullptr, 0) < 0) { + perror("sysctl"); + } return std::string(buffer, size); } @@ -33,7 +34,9 @@ std::string SystemInfo::Pimpl::getCpuModel() { char buffer[512]; size_t size = sizeof(buffer); - if (sysctlbyname("machdep.cpu.brand_string", &buffer, &size, nullptr, 0) < 0) { perror("sysctl"); } + if (sysctlbyname("machdep.cpu.brand_string", &buffer, &size, nullptr, 0) < 0) { + perror("sysctl"); + } return std::string(buffer, size); } @@ -41,21 +44,17 @@ int SystemInfo::Pimpl::getCpuCoreCount() { int buffer; size_t size = sizeof(buffer); - if (sysctlbyname("machdep.cpu.core_count", &buffer, &size, nullptr, 0) < 0) { perror("sysctl"); } + if (sysctlbyname("machdep.cpu.core_count", &buffer, &size, nullptr, 0) < 0) { + perror("sysctl"); + } auto const coreCountStr = std::to_string(buffer); - int coreCount {-1}; + int coreCount{-1}; - try - { + try { coreCount = std::stoi(coreCountStr); - } - catch (std::invalid_argument const& e) - { - } - catch (std::out_of_range const& e) - { - } + } catch (std::invalid_argument const& e) { + } catch (std::out_of_range const& e) {} return coreCount; } @@ -63,21 +62,17 @@ int SystemInfo::Pimpl::getCpuThreadCount() { int buffer; size_t size = sizeof(buffer); - if (sysctlbyname("machdep.cpu.thread_count", &buffer, &size, nullptr, 0) < 0) { perror("sysctl"); } + if (sysctlbyname("machdep.cpu.thread_count", &buffer, &size, nullptr, 0) < 0) { + perror("sysctl"); + } auto const coreCountStr = std::to_string(buffer); - int coreCount {-1}; + int coreCount{-1}; - try - { + try { coreCount = std::stoi(coreCountStr); - } - catch (std::invalid_argument const& e) - { - } - catch (std::out_of_range const& e) - { - } + } catch (std::invalid_argument const& e) { + } catch (std::out_of_range const& e) {} return coreCount; } @@ -85,7 +80,9 @@ std::string SystemInfo::Pimpl::getCpuFeatures() { char buffer[512]; size_t size = sizeof(buffer); - if (sysctlbyname("machdep.cpu.features", &buffer, &size, nullptr, 0) < 0) { perror("sysctl"); } + if (sysctlbyname("machdep.cpu.features", &buffer, &size, nullptr, 0) < 0) { + perror("sysctl"); + } return std::string(buffer, size); } diff --git a/src/moci/core/system/apple/info.hpp b/src/moci/core/system/apple/info.hpp index 655f6a6..76b3231 100644 --- a/src/moci/core/system/apple/info.hpp +++ b/src/moci/core/system/apple/info.hpp @@ -3,10 +3,9 @@ #if defined(MOCI_MAC) -#include + #include -namespace moci -{ +namespace moci { class SystemInfo::Pimpl { public: diff --git a/src/moci/core/system/info.cpp b/src/moci/core/system/info.cpp index 3081585..68a919a 100644 --- a/src/moci/core/system/info.cpp +++ b/src/moci/core/system/info.cpp @@ -3,21 +3,25 @@ #include #if defined(MOCI_LINUX) -#include + #include #elif defined(MOCI_MAC) -#include + #include #elif defined(MOCI_WINDOWS) -#include + #include #endif -namespace moci -{ +namespace moci { auto SystemInfo::getOSName() -> std::string { return Pimpl::getOSName(); } + auto SystemInfo::getVendor() -> std::string { return Pimpl::getVendor(); } + auto SystemInfo::getCpuModel() -> std::string { return Pimpl::getCpuModel(); } + auto SystemInfo::getCpuCoreCount() -> int { return Pimpl::getCpuCoreCount(); } + auto SystemInfo::getCpuThreadCount() -> int { return Pimpl::getCpuThreadCount(); } + auto SystemInfo::getCpuFeatures() -> std::string { return Pimpl::getCpuFeatures(); } } // namespace moci diff --git a/src/moci/core/system/info.hpp b/src/moci/core/system/info.hpp index d0204ed..95ea4fc 100644 --- a/src/moci/core/system/info.hpp +++ b/src/moci/core/system/info.hpp @@ -2,8 +2,7 @@ #include -namespace moci -{ +namespace moci { /** * @brief Query system & machine information. */ diff --git a/src/moci/core/system/info.test.cpp b/src/moci/core/system/info.test.cpp index 3056f3f..5686ec6 100644 --- a/src/moci/core/system/info.test.cpp +++ b/src/moci/core/system/info.test.cpp @@ -9,15 +9,24 @@ #include #if defined(MOCI_LINUX) -TEST_CASE("system: SystemInfoOSName", "[system]") { REQUIRE(moci::SystemInfo::getOSName() == "Linux"); } +TEST_CASE("system: SystemInfoOSName", "[system]") +{ + REQUIRE(moci::SystemInfo::getOSName() == "Linux"); +} #endif #if defined(MOCI_MAC) -TEST_CASE("system: SystemInfoOSName", "[system]") { REQUIRE(moci::SystemInfo::getOSName() == "Darwin"); } +TEST_CASE("system: SystemInfoOSName", "[system]") +{ + REQUIRE(moci::SystemInfo::getOSName() == "Darwin"); +} #endif #if defined(MOCI_WINDOWS) -TEST_CASE("system: SystemInfoOSName", "[system]") { REQUIRE(moci::SystemInfo::getOSName() == "Windows"); } +TEST_CASE("system: SystemInfoOSName", "[system]") +{ + REQUIRE(moci::SystemInfo::getOSName() == "Windows"); +} #endif TEST_CASE("system: SystemInfoDummyChecks", "[system]") diff --git a/src/moci/core/system/linux/info.cpp b/src/moci/core/system/linux/info.cpp index 4d0dc5b..276ab01 100644 --- a/src/moci/core/system/linux/info.cpp +++ b/src/moci/core/system/linux/info.cpp @@ -2,29 +2,28 @@ #if defined(MOCI_LINUX) -#include + #include -#include -#include -#include + #include + #include + #include -#include + #include -namespace moci -{ +namespace moci { auto systemInfoLinuxReadProcInfo() -> std::unordered_map { std::string line; std::ifstream cpuinfo("/proc/cpuinfo"); - if (!cpuinfo.is_open()) { return {}; } + if (!cpuinfo.is_open()) { + return {}; + } - std::unordered_map result {}; - while (getline(cpuinfo, line)) - { + std::unordered_map result{}; + while (getline(cpuinfo, line)) { auto found = std::find(std::begin(line), std::end(line), ':'); - if (found != std::end(line)) - { + if (found != std::end(line)) { auto key = std::string(std::begin(line), found); auto value = std::string(++found, line.end()); Strings::trim(key); @@ -40,7 +39,7 @@ auto systemInfoLinuxReadProcInfo() -> std::unordered_map std::string { - utsname uts {}; + utsname uts{}; uname(&uts); return uts.sysname; } @@ -49,7 +48,9 @@ auto SystemInfo::Pimpl::getVendor() -> std::string { auto const procInfo = systemInfoLinuxReadProcInfo(); auto const vendorID = procInfo.find(std::string("vendor_id")); - if (vendorID != std::end(procInfo)) { return vendorID->second; } + if (vendorID != std::end(procInfo)) { + return vendorID->second; + } return ""; } @@ -57,7 +58,9 @@ auto SystemInfo::Pimpl::getCpuModel() -> std::string { auto const procInfo = systemInfoLinuxReadProcInfo(); auto const vendorID = procInfo.find(std::string("model name")); - if (vendorID != std::end(procInfo)) { return vendorID->second; } + if (vendorID != std::end(procInfo)) { + return vendorID->second; + } return ""; } @@ -65,19 +68,12 @@ auto SystemInfo::Pimpl::getCpuCoreCount() -> int { auto const procInfo = systemInfoLinuxReadProcInfo(); auto const vendorID = procInfo.find(std::string("cpu cores")); - int coreCount {-1}; - if (vendorID != std::end(procInfo)) - { - try - { + int coreCount{-1}; + if (vendorID != std::end(procInfo)) { + try { coreCount = std::stoi(vendorID->second); - } - catch (std::invalid_argument const& e) - { - } - catch (std::out_of_range const& e) - { - } + } catch (std::invalid_argument const& e) { + } catch (std::out_of_range const& e) {} return coreCount; } @@ -88,19 +84,12 @@ auto SystemInfo::Pimpl::getCpuThreadCount() -> int { auto const procInfo = systemInfoLinuxReadProcInfo(); auto const vendorID = procInfo.find(std::string("siblings")); - int threadCount {-1}; - if (vendorID != std::end(procInfo)) - { - try - { + int threadCount{-1}; + if (vendorID != std::end(procInfo)) { + try { threadCount = std::stoi(vendorID->second); - } - catch (std::invalid_argument const& e) - { - } - catch (std::out_of_range const& e) - { - } + } catch (std::invalid_argument const& e) { + } catch (std::out_of_range const& e) {} return threadCount; } @@ -111,7 +100,9 @@ auto SystemInfo::Pimpl::getCpuFeatures() -> std::string { auto const procInfo = systemInfoLinuxReadProcInfo(); auto const vendorID = procInfo.find(std::string("flags")); - if (vendorID != std::end(procInfo)) { return vendorID->second; } + if (vendorID != std::end(procInfo)) { + return vendorID->second; + } return ""; } } // namespace moci diff --git a/src/moci/core/system/linux/info.hpp b/src/moci/core/system/linux/info.hpp index d875df1..255e944 100644 --- a/src/moci/core/system/linux/info.hpp +++ b/src/moci/core/system/linux/info.hpp @@ -3,13 +3,12 @@ #if defined(MOCI_LINUX) -#include + #include -#include -#include + #include + #include -namespace moci -{ +namespace moci { auto systemInfoLinuxReadProcInfo() -> std::unordered_map; class SystemInfo::Pimpl diff --git a/src/moci/core/system/windows/info.cpp b/src/moci/core/system/windows/info.cpp index 658cec0..aeaeccd 100644 --- a/src/moci/core/system/windows/info.cpp +++ b/src/moci/core/system/windows/info.cpp @@ -2,10 +2,9 @@ #if defined(MOCI_WINDOWS) -#include + #include -namespace moci -{ +namespace moci { std::string SystemInfo::Pimpl::getOSName() { return "Windows"; } std::string SystemInfo::Pimpl::getVendor() diff --git a/src/moci/core/system/windows/info.hpp b/src/moci/core/system/windows/info.hpp index 6754700..85684fc 100644 --- a/src/moci/core/system/windows/info.hpp +++ b/src/moci/core/system/windows/info.hpp @@ -3,13 +3,12 @@ #if defined(MOCI_WINDOWS) -#include + #include -#include -#include + #include + #include -namespace moci -{ +namespace moci { class SystemInfo::Pimpl { diff --git a/src/moci/events/input.hpp b/src/moci/events/input.hpp index ebc9c6d..bb0c652 100644 --- a/src/moci/events/input.hpp +++ b/src/moci/events/input.hpp @@ -6,25 +6,33 @@ #include -namespace moci -{ +namespace moci { class Input { public: Input() = default; - Input(const Input&) = delete; - auto operator=(const Input&) -> Input& = delete; + Input(Input const&) = delete; + auto operator=(Input const&) -> Input& = delete; virtual ~Input() = default; - inline static auto isKeyPressed(Key keycode) -> bool { return sInstance->isKeyPressedImpl(keycode); } + inline static auto isKeyPressed(Key keycode) -> bool + { + return sInstance->isKeyPressedImpl(keycode); + } inline static auto isMouseButtonPressed(MouseCode button) -> bool { return sInstance->isMouseButtonPressedImpl(button); } - inline static auto getMousePosition() -> std::pair { return sInstance->getMousePositionImpl(); } + + inline static auto getMousePosition() -> std::pair + { + return sInstance->getMousePositionImpl(); + } + inline static auto getMouseX() -> float { return sInstance->getMouseXImpl(); } + inline static auto getMouseY() -> float { return sInstance->getMouseYImpl(); } private: diff --git a/src/moci/events/key_codes.hpp b/src/moci/events/key_codes.hpp index b4e45f8..93ef0de 100644 --- a/src/moci/events/key_codes.hpp +++ b/src/moci/events/key_codes.hpp @@ -4,8 +4,7 @@ #include #include -namespace moci -{ +namespace moci { // From glfw3.h enum class KeyCode : uint16_t { diff --git a/src/moci/events/layer/layer.cpp b/src/moci/events/layer/layer.cpp index 2f43ed1..f0329c2 100644 --- a/src/moci/events/layer/layer.cpp +++ b/src/moci/events/layer/layer.cpp @@ -2,9 +2,8 @@ #include -namespace moci -{ +namespace moci { -Layer::Layer(std::string debugName) : _debugName(std::move(debugName)) { } +Layer::Layer(std::string debugName) : _debugName(std::move(debugName)) {} } // namespace moci diff --git a/src/moci/events/layer/layer.hpp b/src/moci/events/layer/layer.hpp index f4cc69a..6194627 100644 --- a/src/moci/events/layer/layer.hpp +++ b/src/moci/events/layer/layer.hpp @@ -6,8 +6,7 @@ #include #include -namespace moci -{ +namespace moci { class Layer { @@ -17,10 +16,14 @@ class Layer explicit Layer(std::string name = "Layer"); virtual ~Layer() = default; - virtual void onAttach() { } - virtual void onDetach() { } + virtual void onAttach() {} + + virtual void onDetach() {} + virtual void onUpdate(Timestep ts) { ignoreUnused(ts); } - virtual void onImGuiRender() { } + + virtual void onImGuiRender() {} + virtual void onEvent(Event& event) { ignoreUnused(event); } [[nodiscard]] inline auto getName() const -> std::string const& { return _debugName; } diff --git a/src/moci/events/layer/layer_stack.cpp b/src/moci/events/layer/layer_stack.cpp index 7b3d562..13707d5 100644 --- a/src/moci/events/layer/layer_stack.cpp +++ b/src/moci/events/layer/layer_stack.cpp @@ -3,14 +3,15 @@ #include #include -namespace moci -{ +namespace moci { LayerStack::LayerStack() = default; LayerStack::~LayerStack() { - for (Layer::Ptr& layer : _layers) { layer->onDetach(); } + for (Layer::Ptr& layer : _layers) { + layer->onDetach(); + } } void LayerStack::pushLayer(Layer::Ptr&& layer) diff --git a/src/moci/events/layer/layer_stack.hpp b/src/moci/events/layer/layer_stack.hpp index 7aec621..c4fcdc4 100644 --- a/src/moci/events/layer/layer_stack.hpp +++ b/src/moci/events/layer/layer_stack.hpp @@ -4,8 +4,7 @@ #include -namespace moci -{ +namespace moci { class LayerStack { @@ -15,10 +14,12 @@ class LayerStack void pushLayer(Layer::Ptr&& layer); void pushOverlay(Layer::Ptr&& overlay); + // void PopLayer(Layer* layer); // void PopOverlay(Layer* overlay); auto begin() -> std::vector::iterator { return _layers.begin(); } + auto end() -> std::vector::iterator { return _layers.end(); } private: diff --git a/src/moci/events/layer/layer_stack.test.cpp b/src/moci/events/layer/layer_stack.test.cpp index 5e65a93..747a399 100644 --- a/src/moci/events/layer/layer_stack.test.cpp +++ b/src/moci/events/layer/layer_stack.test.cpp @@ -11,12 +11,12 @@ #include #include -namespace -{ +namespace { class TestLayer : public moci::Layer { public: - explicit TestLayer(std::string n) : moci::Layer(std::move(n)) { } + explicit TestLayer(std::string n) : moci::Layer(std::move(n)) {} + ~TestLayer() override = default; }; } // namespace diff --git a/src/moci/events/mouse_button_codes.hpp b/src/moci/events/mouse_button_codes.hpp index 20f4b3a..521c196 100644 --- a/src/moci/events/mouse_button_codes.hpp +++ b/src/moci/events/mouse_button_codes.hpp @@ -3,8 +3,7 @@ #include #include -namespace moci -{ +namespace moci { // From glfw3.h enum class MouseCode : uint16_t { diff --git a/src/moci/events/timestep.hpp b/src/moci/events/timestep.hpp index ec66759..514525f 100644 --- a/src/moci/events/timestep.hpp +++ b/src/moci/events/timestep.hpp @@ -1,16 +1,16 @@ #pragma once -namespace moci -{ +namespace moci { class Timestep { public: - explicit Timestep(float time = 0.0F) : _time(time) { } + explicit Timestep(float time = 0.0F) : _time(time) {} operator float() const { return _time; } // NOLINT [[nodiscard]] auto getSeconds() const -> float { return _time; } + [[nodiscard]] auto getMilliseconds() const -> float { return _time * 1000.0F; } private: diff --git a/src/moci/events/types/application_event.hpp b/src/moci/events/types/application_event.hpp index e313e42..9e8e89d 100644 --- a/src/moci/events/types/application_event.hpp +++ b/src/moci/events/types/application_event.hpp @@ -4,16 +4,20 @@ #include -namespace moci -{ +namespace moci { class WindowResizeEvent : public Event { public: ~WindowResizeEvent() override = default; - WindowResizeEvent(unsigned int width, unsigned int height) : _width(width), _height(height) { } + + WindowResizeEvent(unsigned int width, unsigned int height) + : _width(width) + , _height(height) + {} [[nodiscard]] inline auto getWidth() const -> unsigned int { return _width; } + [[nodiscard]] inline auto getHeight() const -> unsigned int { return _height; } [[nodiscard]] auto toString() const -> std::string override diff --git a/src/moci/events/types/event.hpp b/src/moci/events/types/event.hpp index 4166c17..2806db4 100644 --- a/src/moci/events/types/event.hpp +++ b/src/moci/events/types/event.hpp @@ -7,8 +7,7 @@ #include #include -namespace moci -{ +namespace moci { // Events in moci are currently blocking, meaning when an event occurs it // immediately gets dispatched and must be dealt with right then an there. @@ -45,25 +44,13 @@ enum EventCategory EventCategoryMouseButton = BIT(4) }; -#define EVENT_CLASS_TYPE(type) \ - static EventType getStaticType() \ - { \ - return EventType::type; \ - } \ - virtual EventType getEventType() const override \ - { \ - return getStaticType(); \ - } \ - virtual std::string_view getName() const override \ - { \ - return #type; \ - } +#define EVENT_CLASS_TYPE(type) \ + static EventType getStaticType() { return EventType::type; } \ + virtual EventType getEventType() const override { return getStaticType(); } \ + virtual std::string_view getName() const override { return #type; } -#define EVENT_CLASS_CATEGORY(category) \ - virtual int getCategoryFlags() const override \ - { \ - return category; \ - } +#define EVENT_CLASS_CATEGORY(category) \ + virtual int getCategoryFlags() const override { return category; } class Event { @@ -74,7 +61,11 @@ class Event [[nodiscard]] virtual auto getEventType() const -> EventType = 0; [[nodiscard]] virtual auto getName() const -> std::string_view = 0; [[nodiscard]] virtual auto getCategoryFlags() const -> int = 0; - [[nodiscard]] virtual auto toString() const -> std::string { return std::string(getName()); } + + [[nodiscard]] virtual auto toString() const -> std::string + { + return std::string(getName()); + } [[nodiscard]] inline auto isInCategory(EventCategory category) const noexcept -> bool { @@ -87,14 +78,13 @@ class Event class EventDispatcher { public: - explicit EventDispatcher(Event& event) : _event(event) { } + explicit EventDispatcher(Event& event) : _event(event) {} // F will be deduced by the compiler template - auto dispatch(const F& func) -> bool + auto dispatch(F const& func) -> bool { - if (_event.getEventType() == T::getStaticType()) - { + if (_event.getEventType() == T::getStaticType()) { _event.Handled = func(static_cast(_event)); return true; } @@ -105,6 +95,9 @@ class EventDispatcher Event& _event; }; -inline auto operator<<(std::ostream& out, const Event& e) -> std::ostream& { return out << e.toString(); } +inline auto operator<<(std::ostream& out, Event const& e) -> std::ostream& +{ + return out << e.toString(); +} } // namespace moci diff --git a/src/moci/events/types/key_event.hpp b/src/moci/events/types/key_event.hpp index 74d4b5b..a36c39e 100644 --- a/src/moci/events/types/key_event.hpp +++ b/src/moci/events/types/key_event.hpp @@ -3,14 +3,15 @@ #include #include -namespace moci -{ +namespace moci { class KeyEvent : public Event { public: ~KeyEvent() override = default; - explicit KeyEvent(Key keycode) : _keyCode(keycode) { } + + explicit KeyEvent(Key keycode) : _keyCode(keycode) {} + [[nodiscard]] inline auto getKeyCode() const -> Key { return _keyCode; } EVENT_CLASS_CATEGORY(EventCategoryKeyboard | EventCategoryInput) @@ -23,13 +24,21 @@ class KeyPressedEvent : public KeyEvent { public: ~KeyPressedEvent() override = default; - KeyPressedEvent(Key keycode, int repeatCount) : KeyEvent(keycode), _repeatCount(repeatCount) { } + + KeyPressedEvent(Key keycode, int repeatCount) + : KeyEvent(keycode) + , _repeatCount(repeatCount) + {} [[nodiscard]] inline auto getRepeatCount() const -> int { return _repeatCount; } [[nodiscard]] auto toString() const -> std::string override { - return fmt::format("KeyPressedEvent: {} ({} repeats)", fmt::streamed(getKeyCode()), _repeatCount); + return fmt::format( + "KeyPressedEvent: {} ({} repeats)", + fmt::streamed(getKeyCode()), + _repeatCount + ); } EVENT_CLASS_TYPE(KeyPressed) @@ -41,7 +50,8 @@ class KeyReleasedEvent : public KeyEvent { public: ~KeyReleasedEvent() override = default; - explicit KeyReleasedEvent(Key keycode) : KeyEvent(keycode) { } + + explicit KeyReleasedEvent(Key keycode) : KeyEvent(keycode) {} [[nodiscard]] auto toString() const -> std::string override { @@ -55,7 +65,8 @@ class KeyTypedEvent : public KeyEvent { public: ~KeyTypedEvent() override = default; - explicit KeyTypedEvent(Key keycode) : KeyEvent(keycode) { } + + explicit KeyTypedEvent(Key keycode) : KeyEvent(keycode) {} [[nodiscard]] auto toString() const -> std::string override { diff --git a/src/moci/events/types/mouse_event.hpp b/src/moci/events/types/mouse_event.hpp index b60bfdc..d7a011a 100644 --- a/src/moci/events/types/mouse_event.hpp +++ b/src/moci/events/types/mouse_event.hpp @@ -4,16 +4,17 @@ #include #include -namespace moci -{ +namespace moci { class MouseMovedEvent : public Event { public: ~MouseMovedEvent() override = default; - MouseMovedEvent(float x, float y) : _mouseX(x), _mouseY(y) { } + + MouseMovedEvent(float x, float y) : _mouseX(x), _mouseY(y) {} [[nodiscard]] inline auto getX() const -> float { return _mouseX; } + [[nodiscard]] inline auto getY() const -> float { return _mouseY; } [[nodiscard]] auto toString() const -> std::string override @@ -31,9 +32,12 @@ class MouseScrolledEvent : public Event { public: ~MouseScrolledEvent() override = default; - MouseScrolledEvent(float xOffset, float yOffset) : _xOffset(xOffset), _yOffset(yOffset) { } + + MouseScrolledEvent(float xOffset, float yOffset) : _xOffset(xOffset), _yOffset(yOffset) + {} [[nodiscard]] inline auto getXOffset() const -> float { return _xOffset; } + [[nodiscard]] inline auto getYOffset() const -> float { return _yOffset; } [[nodiscard]] auto toString() const -> std::string override @@ -51,7 +55,9 @@ class MouseButtonEvent : public Event { public: ~MouseButtonEvent() override = default; - explicit MouseButtonEvent(MouseCode button) : _button(button) { } + + explicit MouseButtonEvent(MouseCode button) : _button(button) {} + [[nodiscard]] inline auto getMouseButton() const -> MouseCode { return _button; } EVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput) @@ -63,11 +69,15 @@ class MouseButtonPressedEvent : public MouseButtonEvent { public: ~MouseButtonPressedEvent() override = default; - explicit MouseButtonPressedEvent(MouseCode button) : MouseButtonEvent(button) { } + + explicit MouseButtonPressedEvent(MouseCode button) : MouseButtonEvent(button) {} [[nodiscard]] auto toString() const -> std::string override { - return fmt::format("MouseButtonPressedEvent: {}", static_cast(getMouseButton())); + return fmt::format( + "MouseButtonPressedEvent: {}", + static_cast(getMouseButton()) + ); } EVENT_CLASS_TYPE(MouseButtonPressed) @@ -77,11 +87,15 @@ class MouseButtonReleasedEvent : public MouseButtonEvent { public: ~MouseButtonReleasedEvent() override = default; - explicit MouseButtonReleasedEvent(MouseCode button) : MouseButtonEvent(button) { } + + explicit MouseButtonReleasedEvent(MouseCode button) : MouseButtonEvent(button) {} [[nodiscard]] auto toString() const -> std::string override { - return fmt::format("MouseButtonReleasedEvent: {}", static_cast(getMouseButton())); + return fmt::format( + "MouseButtonReleasedEvent: {}", + static_cast(getMouseButton()) + ); } EVENT_CLASS_TYPE(MouseButtonReleased) diff --git a/src/moci/graphics/color.hpp b/src/moci/graphics/color.hpp index 82fe82f..b62d3bd 100644 --- a/src/moci/graphics/color.hpp +++ b/src/moci/graphics/color.hpp @@ -4,29 +4,41 @@ #include -namespace moci -{ +namespace moci { class ColorRGBA32 { public: constexpr ColorRGBA32() noexcept = default; - constexpr ColorRGBA32(float r, float g, float b) noexcept : _data {r, g, b, 1.0F} { } - constexpr ColorRGBA32(float r, float g, float b, float alpha) noexcept : _data {r, g, b, alpha} { } + + constexpr ColorRGBA32(float r, float g, float b) noexcept : _data{r, g, b, 1.0F} {} + + constexpr ColorRGBA32(float r, float g, float b, float alpha) noexcept + : _data{r, g, b, alpha} + {} [[nodiscard]] constexpr auto red() const noexcept -> float { return _data[0]; } + [[nodiscard]] constexpr auto green() const noexcept -> float { return _data[1]; } + [[nodiscard]] constexpr auto blue() const noexcept -> float { return _data[2]; } + [[nodiscard]] constexpr auto alpha() const noexcept -> float { return _data[3]; } auto red(float r) noexcept -> void { _data[0] = r; } + auto green(float g) noexcept -> void { _data[1] = g; } + auto blue(float b) noexcept -> void { _data[2] = b; } + auto alpha(float a) noexcept -> void { _data[3] = a; } - explicit constexpr operator glm::vec4() const noexcept { return {_data[0], _data[1], _data[2], _data[3]}; } + explicit constexpr operator glm::vec4() const noexcept + { + return {_data[0], _data[1], _data[2], _data[3]}; + } private: - std::array _data {0.0F, 0.0F, 0.0F, 0.0F}; + std::array _data{0.0F, 0.0F, 0.0F, 0.0F}; }; class Colors diff --git a/src/moci/graphics/color.test.cpp b/src/moci/graphics/color.test.cpp index 9803cbf..0e84308 100644 --- a/src/moci/graphics/color.test.cpp +++ b/src/moci/graphics/color.test.cpp @@ -8,7 +8,7 @@ TEST_CASE("graphics: ColorDefaultConstructor", "[graphics]") { - moci::ColorRGBA32 color {}; + moci::ColorRGBA32 color{}; REQUIRE(color.red() == 0.0F); REQUIRE(color.green() == 0.0F); REQUIRE(color.blue() == 0.0F); @@ -17,7 +17,7 @@ TEST_CASE("graphics: ColorDefaultConstructor", "[graphics]") TEST_CASE("graphics: ColorRGBConstructor", "[graphics]") { - moci::ColorRGBA32 color {1.0F, 1.0F, 1.0F}; + moci::ColorRGBA32 color{1.0F, 1.0F, 1.0F}; REQUIRE(color.red() == 1.0F); REQUIRE(color.green() == 1.0F); @@ -27,7 +27,7 @@ TEST_CASE("graphics: ColorRGBConstructor", "[graphics]") TEST_CASE("graphics: ColorRGBAConstructor", "[graphics]") { - moci::ColorRGBA32 color {1.0F, 1.0F, 1.0F, 0.5F}; + moci::ColorRGBA32 color{1.0F, 1.0F, 1.0F, 0.5F}; REQUIRE(color.red() == 1.0F); REQUIRE(color.green() == 1.0F); @@ -37,7 +37,7 @@ TEST_CASE("graphics: ColorRGBAConstructor", "[graphics]") TEST_CASE("graphics: ColorGetData", "[graphics]") { - constexpr moci::ColorRGBA32 color {}; + constexpr moci::ColorRGBA32 color{}; auto const data = static_cast(color); REQUIRE(data.r == 0.0F); @@ -48,7 +48,7 @@ TEST_CASE("graphics: ColorGetData", "[graphics]") TEST_CASE("graphics: ColorSetRGBA", "[graphics]") { - moci::ColorRGBA32 color {}; + moci::ColorRGBA32 color{}; color.red(1.0F); color.green(1.0F); color.blue(1.0F); diff --git a/src/moci/graphics/font.cpp b/src/moci/graphics/font.cpp index 809cf33..ba4dcdb 100644 --- a/src/moci/graphics/font.cpp +++ b/src/moci/graphics/font.cpp @@ -4,12 +4,17 @@ #include -namespace moci -{ -Typeface::Typeface(std::string name) : _name(std::move(name)) { } - -void Typeface::addCharacter(char c, std::uint32_t height, std::uint32_t width, Point topLeft, - std::uint32_t advance, Buffer buffer) +namespace moci { +Typeface::Typeface(std::string name) : _name(std::move(name)) {} + +void Typeface::addCharacter( + char c, + std::uint32_t height, + std::uint32_t width, + Point topLeft, + std::uint32_t advance, + Buffer buffer +) { addCharacter(c, {height, width, topLeft, advance, std::move(buffer)}); } @@ -21,9 +26,8 @@ void Typeface::addCharacter(char c, Character const& character) auto Typeface::getWidthForString(std::string const& text, float scale) -> std::uint32_t { - auto position = Point {}; - for (auto const c : text) - { + auto position = Point{}; + for (auto const c : text) { auto const& ch = _characters[c]; // float const xpos = position.getX() + ch.topLeft.getX() * scale; diff --git a/src/moci/graphics/font.hpp b/src/moci/graphics/font.hpp index 7900158..2e139f6 100644 --- a/src/moci/graphics/font.hpp +++ b/src/moci/graphics/font.hpp @@ -8,8 +8,7 @@ #include #include -namespace moci -{ +namespace moci { class Typeface { @@ -18,27 +17,45 @@ class Typeface struct Character { - std::uint32_t width {}; - std::uint32_t height {}; - Point topLeft {}; - std::uint32_t advance {}; - Buffer buffer {}; + std::uint32_t width{}; + std::uint32_t height{}; + Point topLeft{}; + std::uint32_t advance{}; + Buffer buffer{}; }; explicit Typeface(std::string name); - void addCharacter(char c, std::uint32_t height, std::uint32_t width, Point topLeft, - std::uint32_t advance, Buffer buffer); + void addCharacter( + char c, + std::uint32_t height, + std::uint32_t width, + Point topLeft, + std::uint32_t advance, + Buffer buffer + ); void addCharacter(char c, Character const& character); - [[nodiscard]] auto getName() const noexcept -> std::string_view { return std::string_view(_name); } - [[nodiscard]] auto getNumCharacters() const noexcept -> std::size_t { return _characters.size(); } - [[nodiscard]] auto getCharacter(char c) const noexcept -> Character const& { return (*_characters.find(c)).second; } + [[nodiscard]] auto getName() const noexcept -> std::string_view + { + return std::string_view(_name); + } + + [[nodiscard]] auto getNumCharacters() const noexcept -> std::size_t + { + return _characters.size(); + } + + [[nodiscard]] auto getCharacter(char c) const noexcept -> Character const& + { + return (*_characters.find(c)).second; + } - [[nodiscard]] auto getWidthForString(std::string const& text, float scale = 1.0F) -> std::uint32_t; + [[nodiscard]] auto getWidthForString(std::string const& text, float scale = 1.0F) + -> std::uint32_t; private: - std::string _name {}; - std::map _characters {}; + std::string _name{}; + std::map _characters{}; }; class Font diff --git a/src/moci/graphics/font.test.cpp b/src/moci/graphics/font.test.cpp index de2379d..6c879ae 100644 --- a/src/moci/graphics/font.test.cpp +++ b/src/moci/graphics/font.test.cpp @@ -9,13 +9,13 @@ TEST_CASE("graphics: TypefaceConstruct", "[font][graphics]") { - moci::Typeface face {"comic-sans"}; + moci::Typeface face{"comic-sans"}; REQUIRE(face.getName() == "comic-sans"); } TEST_CASE("graphics: TypefaceGetWidthForString", "[font][graphics]") { - const auto* const path = "moci_test_data/OpenSans-Bold.ttf"; + auto const* const path = "moci_test_data/OpenSans-Bold.ttf"; auto const opt = moci::FreetypeLibrary::createTypefaceFromFont(path); REQUIRE(opt.has_value() == true); diff --git a/src/moci/graphics/freetype/library.cpp b/src/moci/graphics/freetype/library.cpp index 03255fa..80c4af1 100644 --- a/src/moci/graphics/freetype/library.cpp +++ b/src/moci/graphics/freetype/library.cpp @@ -7,30 +7,39 @@ #include -namespace moci +namespace moci { +auto FreetypeLibrary::createTypefaceFromFont(std::string const& fontPath) + -> std::optional { -auto FreetypeLibrary::createTypefaceFromFont(const std::string& fontPath) -> std::optional -{ - if (fontPath.empty()) { return std::nullopt; } + if (fontPath.empty()) { + return std::nullopt; + } FT_Library ft = nullptr; - if (FT_Init_FreeType(&ft) != 0) { return std::nullopt; } + if (FT_Init_FreeType(&ft) != 0) { + return std::nullopt; + } auto closeLibrary = moci::makeScopeGuard([&ft]() { FT_Done_FreeType(ft); }); FT_Face face = nullptr; - if (FT_New_Face(ft, fontPath.c_str(), 0, &face) != 0) { return std::nullopt; } + if (FT_New_Face(ft, fontPath.c_str(), 0, &face) != 0) { + return std::nullopt; + } auto closeFace = moci::makeScopeGuard([&face]() { FT_Done_Face(face); }); FT_Set_Pixel_Sizes(face, 0, 48); - Typeface result {fontPath}; - for (std::uint8_t c = 0; c < 128; c++) - { + Typeface result{fontPath}; + for (std::uint8_t c = 0; c < 128; c++) { // Load character glyph - if (FT_Load_Char(face, c, FT_LOAD_RENDER) != 0) { continue; } + if (FT_Load_Char(face, c, FT_LOAD_RENDER) != 0) { + continue; + } auto buffer = std::vector( - face->glyph->bitmap.buffer, // - face->glyph->bitmap.buffer + (static_cast(face->glyph->bitmap.width * face->glyph->bitmap.rows)) // + face->glyph->bitmap.buffer, // + face->glyph->bitmap.buffer + + (static_cast(face->glyph->bitmap.width * face->glyph->bitmap.rows) + ) // ); result.addCharacter( // diff --git a/src/moci/graphics/freetype/library.hpp b/src/moci/graphics/freetype/library.hpp index 04dad92..295884f 100644 --- a/src/moci/graphics/freetype/library.hpp +++ b/src/moci/graphics/freetype/library.hpp @@ -4,8 +4,7 @@ #include -namespace moci -{ +namespace moci { /** * @brief Wrapper around freetype. @@ -21,7 +20,8 @@ class FreetypeLibrary /** * @brief Create a new typeface from a font file. */ - static auto createTypefaceFromFont(const std::string& fontPath) -> std::optional; + static auto createTypefaceFromFont(std::string const& fontPath) + -> std::optional; private: }; diff --git a/src/moci/graphics/freetype/library.test.cpp b/src/moci/graphics/freetype/library.test.cpp index 6479009..ba7f468 100644 --- a/src/moci/graphics/freetype/library.test.cpp +++ b/src/moci/graphics/freetype/library.test.cpp @@ -8,7 +8,7 @@ TEST_CASE("graphics/freetype: FreetypeCreateTypeface", "[graphics][font]") { - const auto* const path = "moci_test_data/OpenSans-Bold.ttf"; + auto const* const path = "moci_test_data/OpenSans-Bold.ttf"; auto const typeface = moci::FreetypeLibrary::createTypefaceFromFont(path); REQUIRE(typeface.has_value() == true); REQUIRE(typeface.value().getNumCharacters() == 128); diff --git a/src/moci/graphics/image.cpp b/src/moci/graphics/image.cpp index 3110fe1..4fae611 100644 --- a/src/moci/graphics/image.cpp +++ b/src/moci/graphics/image.cpp @@ -7,23 +7,22 @@ #include "stb_image.h" #include "stb_image_resize.h" -namespace moci -{ +namespace moci { Image::Image(std::string const& path) { loadFromFile(path); } auto Image::loadFromFile(std::string const& path) -> bool { auto* data = stbi_load(path.c_str(), &_width, &_height, &_numChannels, 0); - if (data == nullptr) - { + if (data == nullptr) { MOCI_CORE_ERROR("Image loading: {}", path); stbi_image_free(data); return false; } auto* start = reinterpret_cast(data); - auto* end = reinterpret_cast(data) + static_cast(_width * _height * _numChannels); - _data = std::vector(start, end); + auto* end = reinterpret_cast(data) + + static_cast(_width * _height * _numChannels); + _data = std::vector(start, end); stbi_image_free(data); diff --git a/src/moci/graphics/image.hpp b/src/moci/graphics/image.hpp index 28ceb47..a4e475e 100644 --- a/src/moci/graphics/image.hpp +++ b/src/moci/graphics/image.hpp @@ -6,8 +6,7 @@ #include #include -namespace moci -{ +namespace moci { class Image { public: @@ -19,7 +18,9 @@ class Image [[nodiscard]] auto empty() const noexcept -> bool { return _data.empty(); } [[nodiscard]] auto getWidth() const noexcept -> int { return _width; } + [[nodiscard]] auto getHeight() const noexcept -> int { return _height; } + [[nodiscard]] auto getNumChannels() const noexcept -> int { return _numChannels; } [[nodiscard]] auto data() noexcept -> std::span { return _data; } diff --git a/src/moci/graphics/image.test.cpp b/src/moci/graphics/image.test.cpp index 9a4c30c..c966bca 100644 --- a/src/moci/graphics/image.test.cpp +++ b/src/moci/graphics/image.test.cpp @@ -8,7 +8,7 @@ TEST_CASE("graphics: ImageDefaultConstructor", "[graphics]") { - moci::Image img {}; + moci::Image img{}; REQUIRE(img.getWidth() == 0); REQUIRE(img.getHeight() == 0); REQUIRE(img.empty() == true); @@ -17,7 +17,7 @@ TEST_CASE("graphics: ImageDefaultConstructor", "[graphics]") TEST_CASE("graphics: ImagePathConstructor", "[graphics]") { - moci::Image img {"moci_test_data/colors.png"}; + moci::Image img{"moci_test_data/colors.png"}; REQUIRE(img.getWidth() == 256); REQUIRE(img.getHeight() == 256); REQUIRE(img.getNumChannels() == 3); @@ -27,7 +27,7 @@ TEST_CASE("graphics: ImagePathConstructor", "[graphics]") TEST_CASE("graphics: ImageLoadFromFileSuccess", "[graphics]") { - moci::Image img {}; + moci::Image img{}; REQUIRE(img.loadFromFile("moci_test_data/colors.png") == true); REQUIRE(img.getWidth() == 256); REQUIRE(img.getHeight() == 256); @@ -38,7 +38,7 @@ TEST_CASE("graphics: ImageLoadFromFileSuccess", "[graphics]") TEST_CASE("graphics: ImageLoadFromFileFail", "[graphics]") { - moci::Image img {}; + moci::Image img{}; REQUIRE(img.loadFromFile("noexist.png") == false); REQUIRE(img.getWidth() == 0); REQUIRE(img.getHeight() == 0); diff --git a/src/moci/graphics/obj/file.cpp b/src/moci/graphics/obj/file.cpp index 428cea6..b427372 100644 --- a/src/moci/graphics/obj/file.cpp +++ b/src/moci/graphics/obj/file.cpp @@ -7,51 +7,54 @@ #include #include -namespace moci -{ +namespace moci { -OBJFile::OBJFile(std::string path) : _path(std::move(path)) { } +OBJFile::OBJFile(std::string path) : _path(std::move(path)) {} auto OBJFile::parse() -> bool { std::string line; std::ifstream objFile(_path); - if (!objFile.is_open()) { return false; } + if (!objFile.is_open()) { + return false; + } auto guard = makeScopeGuard([&]() { objFile.close(); }); - while (getline(objFile, line)) - { + while (getline(objFile, line)) { // Remove whitespace Strings::trim(line); // Ignore empty lines - if (line.empty()) { continue; } + if (line.empty()) { + continue; + } // Ignore comments - if (line[0] == '#') { continue; } + if (line[0] == '#') { + continue; + } // Ignore g - if (line[0] == 'g') { continue; } + if (line[0] == 'g') { + continue; + } // Vertex position 'v' - if (line[0] == 'v' && line[1] == ' ') - { + if (line[0] == 'v' && line[1] == ' ') { line = line.substr(2); _vertices.push_back(parseLineToVec3(line)); continue; } // Vertex normal 'vn' - if (line[0] == 'v' && line[1] == 'n') - { + if (line[0] == 'v' && line[1] == 'n') { line = line.substr(3); _normals.push_back(parseLineToVec3(line)); continue; } // Face 'f' - if (line[0] == 'f' && line[1] == ' ') - { + if (line[0] == 'f' && line[1] == ' ') { line = line.substr(2); parseLineToFace(line); continue; @@ -65,28 +68,29 @@ auto OBJFile::parseLineToVec3(std::string& line) -> glm::vec3 { auto splits = Strings::split(line, ' '); - std::for_each(std::begin(splits), std::end(splits), [](auto& split) { Strings::trim(split); }); - splits.erase( // - std::remove_if(splits.begin(), // - splits.end(), // - [](auto const& split) { return split.empty(); }), // - splits.end() // + std::for_each(std::begin(splits), std::end(splits), [](auto& split) { + Strings::trim(split); + }); + splits.erase( // + std::remove_if( + splits.begin(), // + splits.end(), // + [](auto const& split) { return split.empty(); } + ), // + splits.end() // ); MOCI_CORE_ASSERT(splits.size() == 3, "Only vec3 supported for positions"); - float x {}; - float y {}; - float z {}; + float x{}; + float y{}; + float z{}; - try - { + try { x = std::stof(splits[0]); y = std::stof(splits[1]); z = std::stof(splits[2]); - } - catch (...) - { + } catch (...) { MOCI_CORE_CRITICAL("Exception during string to float conversion"); } @@ -96,54 +100,63 @@ auto OBJFile::parseLineToVec3(std::string& line) -> glm::vec3 void OBJFile::parseLineToFace(std::string& line) { auto splits = Strings::split(line, ' '); - std::for_each(std::begin(splits), std::end(splits), [](auto& split) { Strings::trim(split); }); - splits.erase( // - std::remove_if(splits.begin(), // - splits.end(), // - [](auto const& split) { return split.empty(); }), // - splits.end() // + std::for_each(std::begin(splits), std::end(splits), [](auto& split) { + Strings::trim(split); + }); + splits.erase( // + std::remove_if( + splits.begin(), // + splits.end(), // + [](auto const& split) { return split.empty(); } + ), // + splits.end() // ); MOCI_CORE_ASSERT(splits.size() == 3, ""); - for (auto& split : splits) - { + for (auto& split : splits) { auto indices = Strings::split(split, '/'); - if (indices.size() == 3) - { + if (indices.size() == 3) { auto const vertexIdx = Strings::toInt(indices[0]); // auto const textureIdx = Strings::ToInt(indices[1]); auto const normalIdx = Strings::toInt(indices[2]); - MOCI_CORE_ASSERT(vertexIdx.has_value() == true, "The vertex position should never be empty"); + MOCI_CORE_ASSERT( + vertexIdx.has_value() == true, + "The vertex position should never be empty" + ); auto const vertex = _vertices.at(vertexIdx.value() - 1); auto const normal = _normals.at(normalIdx.value() - 1); - auto const texture = glm::vec2 {}; + auto const texture = glm::vec2{}; _model.push_back({vertex, normal, texture}); } - if (indices.size() == 2) - { + if (indices.size() == 2) { auto const vertexIdx = Strings::toInt(indices[0]); // auto const textureIdx = Strings::ToInt(indices[1]); - MOCI_CORE_ASSERT(vertexIdx.has_value() == true, "The vertex position should never be empty"); + MOCI_CORE_ASSERT( + vertexIdx.has_value() == true, + "The vertex position should never be empty" + ); auto const vertex = _vertices.at(vertexIdx.value() - 1); - auto const normal = glm::vec3 {}; - auto const texture = glm::vec2 {}; + auto const normal = glm::vec3{}; + auto const texture = glm::vec2{}; _model.push_back({vertex, normal, texture}); } - if (indices.size() == 1) - { + if (indices.size() == 1) { auto const vertexIdx = Strings::toInt(indices[0]); - MOCI_CORE_ASSERT(vertexIdx.has_value() == true, "The vertex position should never be empty"); + MOCI_CORE_ASSERT( + vertexIdx.has_value() == true, + "The vertex position should never be empty" + ); auto const vertex = _vertices.at(vertexIdx.value() - 1); - auto const normal = glm::vec3 {}; - auto const texture = glm::vec2 {}; + auto const normal = glm::vec3{}; + auto const texture = glm::vec2{}; _model.push_back({vertex, normal, texture}); } diff --git a/src/moci/graphics/obj/file.hpp b/src/moci/graphics/obj/file.hpp index bebfb53..87c1dc2 100644 --- a/src/moci/graphics/obj/file.hpp +++ b/src/moci/graphics/obj/file.hpp @@ -8,8 +8,7 @@ #include #include -namespace moci -{ +namespace moci { /** * @brief Simple Wavefront OBJ file loader. */ diff --git a/src/moci/graphics_extra/camera.cpp b/src/moci/graphics_extra/camera.cpp index 731c5b8..6768104 100644 --- a/src/moci/graphics_extra/camera.cpp +++ b/src/moci/graphics_extra/camera.cpp @@ -8,11 +8,11 @@ #include -namespace moci -{ +namespace moci { OrthographicCamera::OrthographicCamera(float left, float right, float bottom, float top) - : _projectionMatrix(glm::ortho(left, right, bottom, top, -1.0F, 1.0F)), _viewMatrix(1.0F) + : _projectionMatrix(glm::ortho(left, right, bottom, top, -1.0F, 1.0F)) + , _viewMatrix(1.0F) { _viewProjectionMatrix = _projectionMatrix * _viewMatrix; } @@ -25,8 +25,9 @@ void OrthographicCamera::setProjection(float left, float right, float bottom, fl void OrthographicCamera::recalculateViewMatrix() { - glm::mat4 transform = glm::translate(glm::mat4(1.0F), _position) - * glm::rotate(glm::mat4(1.0F), glm::radians(_rotation), glm::vec3(0, 0, 1)); + glm::mat4 transform + = glm::translate(glm::mat4(1.0F), _position) + * glm::rotate(glm::mat4(1.0F), glm::radians(_rotation), glm::vec3(0, 0, 1)); _viewMatrix = glm::inverse(transform); _viewProjectionMatrix = _projectionMatrix * _viewMatrix; @@ -34,42 +35,54 @@ void OrthographicCamera::recalculateViewMatrix() OrthographicCameraController::OrthographicCameraController(float aspectRatio, bool rotation) : _aspectRatio(aspectRatio) - , _camera(-_aspectRatio * _zoomLevel, _aspectRatio * _zoomLevel, -_zoomLevel, _zoomLevel) + , _camera( + -_aspectRatio * _zoomLevel, + _aspectRatio * _zoomLevel, + -_zoomLevel, + _zoomLevel + ) , _rotation(rotation) -{ -} +{} void OrthographicCameraController::onUpdate(Timestep ts) { - if (Input::isKeyPressed(moci::Key::A)) - { - _cameraPosition.x -= cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; - _cameraPosition.y -= sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; - } - else if (Input::isKeyPressed(moci::Key::D)) - { - _cameraPosition.x += cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; - _cameraPosition.y += sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + if (Input::isKeyPressed(moci::Key::A)) { + _cameraPosition.x + -= cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + _cameraPosition.y + -= sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + } else if (Input::isKeyPressed(moci::Key::D)) { + _cameraPosition.x + += cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + _cameraPosition.y + += sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; } - if (Input::isKeyPressed(moci::Key::W)) - { - _cameraPosition.x += -sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; - _cameraPosition.y += cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; - } - else if (Input::isKeyPressed(moci::Key::S)) - { - _cameraPosition.x -= -sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; - _cameraPosition.y -= cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + if (Input::isKeyPressed(moci::Key::W)) { + _cameraPosition.x + += -sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + _cameraPosition.y + += cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + } else if (Input::isKeyPressed(moci::Key::S)) { + _cameraPosition.x + -= -sin(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; + _cameraPosition.y + -= cos(glm::radians(_cameraRotation)) * _cameraTranslationSpeed * ts; } - if (_rotation) - { - if (Input::isKeyPressed(moci::Key::Q)) { _cameraRotation += _cameraRotationSpeed * ts; } - if (Input::isKeyPressed(moci::Key::E)) { _cameraRotation -= _cameraRotationSpeed * ts; } + if (_rotation) { + if (Input::isKeyPressed(moci::Key::Q)) { + _cameraRotation += _cameraRotationSpeed * ts; + } + if (Input::isKeyPressed(moci::Key::E)) { + _cameraRotation -= _cameraRotationSpeed * ts; + } - if (_cameraRotation > 180.0F) { _cameraRotation -= 360.0F; } - else if (_cameraRotation <= -180.0F) { _cameraRotation += 360.0F; } + if (_cameraRotation > 180.0F) { + _cameraRotation -= 360.0F; + } else if (_cameraRotation <= -180.0F) { + _cameraRotation += 360.0F; + } _camera.setRotation(_cameraRotation); } @@ -82,22 +95,36 @@ void OrthographicCameraController::onUpdate(Timestep ts) void OrthographicCameraController::onEvent(Event& e) { EventDispatcher dispatcher(e); - dispatcher.dispatch(MOCI_EVENT_METHOD(OrthographicCameraController::onMouseScrolled)); - dispatcher.dispatch(MOCI_EVENT_METHOD(OrthographicCameraController::onWindowResized)); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OrthographicCameraController::onMouseScrolled) + ); + dispatcher.dispatch( + MOCI_EVENT_METHOD(OrthographicCameraController::onWindowResized) + ); } auto OrthographicCameraController::onMouseScrolled(MouseScrolledEvent& e) -> bool { _zoomLevel -= e.getYOffset() * 0.25F; _zoomLevel = std::max(_zoomLevel, 0.25F); - _camera.setProjection(-_aspectRatio * _zoomLevel, _aspectRatio * _zoomLevel, -_zoomLevel, _zoomLevel); + _camera.setProjection( + -_aspectRatio * _zoomLevel, + _aspectRatio * _zoomLevel, + -_zoomLevel, + _zoomLevel + ); return false; } auto OrthographicCameraController::onWindowResized(WindowResizeEvent& e) -> bool { _aspectRatio = (float)e.getWidth() / (float)e.getHeight(); - _camera.setProjection(-_aspectRatio * _zoomLevel, _aspectRatio * _zoomLevel, -_zoomLevel, _zoomLevel); + _camera.setProjection( + -_aspectRatio * _zoomLevel, + _aspectRatio * _zoomLevel, + -_zoomLevel, + _zoomLevel + ); return false; } } // namespace moci diff --git a/src/moci/graphics_extra/camera.hpp b/src/moci/graphics_extra/camera.hpp index 5ccdb6a..bc42c39 100644 --- a/src/moci/graphics_extra/camera.hpp +++ b/src/moci/graphics_extra/camera.hpp @@ -7,8 +7,7 @@ #include "glm/glm.hpp" -namespace moci -{ +namespace moci { class OrthographicCamera { @@ -17,30 +16,40 @@ class OrthographicCamera void setProjection(float left, float right, float bottom, float top); - [[nodiscard]] auto getPosition() const -> const glm::vec3& { return _position; } - void setPosition(const glm::vec3& position) + [[nodiscard]] auto getPosition() const -> glm::vec3 const& { return _position; } + + void setPosition(glm::vec3 const& position) { _position = position; recalculateViewMatrix(); } [[nodiscard]] auto getRotation() const -> float { return _rotation; } + void setRotation(float rotation) { _rotation = rotation; recalculateViewMatrix(); } - [[nodiscard]] auto getProjectionMatrix() const -> const glm::mat4& { return _projectionMatrix; } - [[nodiscard]] auto getViewMatrix() const -> const glm::mat4& { return _viewMatrix; } - [[nodiscard]] auto getViewProjectionMatrix() const -> const glm::mat4& { return _viewProjectionMatrix; } + [[nodiscard]] auto getProjectionMatrix() const -> glm::mat4 const& + { + return _projectionMatrix; + } + + [[nodiscard]] auto getViewMatrix() const -> glm::mat4 const& { return _viewMatrix; } + + [[nodiscard]] auto getViewProjectionMatrix() const -> glm::mat4 const& + { + return _viewProjectionMatrix; + } private: void recalculateViewMatrix(); glm::mat4 _projectionMatrix; glm::mat4 _viewMatrix; - glm::mat4 _viewProjectionMatrix {}; + glm::mat4 _viewProjectionMatrix{}; glm::vec3 _position = {0.0F, 0.0F, 0.0F}; float _rotation = 0.0F; @@ -55,9 +64,11 @@ class OrthographicCameraController void onEvent(Event& e); auto getCamera() -> OrthographicCamera& { return _camera; } - [[nodiscard]] auto getCamera() const -> const OrthographicCamera& { return _camera; } + + [[nodiscard]] auto getCamera() const -> OrthographicCamera const& { return _camera; } [[nodiscard]] auto getZoomLevel() const -> float { return _zoomLevel; } + void setZoomLevel(float level) { _zoomLevel = level; } private: diff --git a/src/moci/graphics_extra/camera.test.cpp b/src/moci/graphics_extra/camera.test.cpp index e791936..b0e815f 100644 --- a/src/moci/graphics_extra/camera.test.cpp +++ b/src/moci/graphics_extra/camera.test.cpp @@ -10,9 +10,12 @@ TEST_CASE("graphics_extra: OrthographicCamera", "[render]") { - moci::OrthographicCamera camera {0.0F, 100.0F, 100.0F, 0.0F}; - REQUIRE(camera.getPosition() == glm::vec3 {}); + moci::OrthographicCamera camera{0.0F, 100.0F, 100.0F, 0.0F}; + REQUIRE(camera.getPosition() == glm::vec3{}); REQUIRE(camera.getRotation() == 0.0F); - REQUIRE(camera.getViewMatrix() == glm::mat4 {1.0F}); - REQUIRE(camera.getViewProjectionMatrix() == glm::ortho(0.0F, 100.0F, 100.0F, 0.0F, -1.0F, 1.0F)); + REQUIRE(camera.getViewMatrix() == glm::mat4{1.0F}); + REQUIRE( + camera.getViewProjectionMatrix() + == glm::ortho(0.0F, 100.0F, 100.0F, 0.0F, -1.0F, 1.0F) + ); } diff --git a/src/moci/graphics_extra/light.hpp b/src/moci/graphics_extra/light.hpp index 9509d28..fc86924 100644 --- a/src/moci/graphics_extra/light.hpp +++ b/src/moci/graphics_extra/light.hpp @@ -18,8 +18,7 @@ #include "glm/gtx/quaternion.hpp" -namespace moci -{ +namespace moci { struct Light { struct Vertex @@ -36,28 +35,34 @@ struct Light std::shared_ptr vbo = nullptr; std::shared_ptr ibo = nullptr; std::shared_ptr vao = nullptr; - Mesh lightMesh_ {"src/app/sandbox3D/assets/models/sphere.obj"}; + Mesh lightMesh_{"src/app/sandbox3D/assets/models/sphere.obj"}; std::vector vertices = {}; public: Light() { #if defined(MOCI_API_OPENGL_LEGACY) - shader = RenderFactory::makeShader("src/app/sandbox3D/assets/shader/es2_light_source.glsl"); + shader = RenderFactory::makeShader( + "src/app/sandbox3D/assets/shader/es2_light_source.glsl" + ); #else - shader = RenderFactory::makeShader("src/app/sandbox3D/assets/shader/gl4_light_source.glsl"); + shader = RenderFactory::makeShader( + "src/app/sandbox3D/assets/shader/gl4_light_source.glsl" + ); #endif shader->bind(); BufferLayout lightLayout = { - {ShaderDataType::Float3, "a_Position"}, // - {ShaderDataType::Float4, "a_Color"}, // + {ShaderDataType::Float3, "a_Position"}, // + {ShaderDataType::Float4, "a_Color" }, // }; - auto const size = static_cast(lightMesh_.getVertices().size() * sizeof(Light::Vertex)); + auto const size = static_cast( + lightMesh_.getVertices().size() * sizeof(Light::Vertex) + ); vbo.reset(RenderFactory::makeVertexBuffer(nullptr, size, true)); vbo->setLayout(lightLayout); vbo->unbind(); - auto indexBufferSpecs = IndexBufferSpecs {}; + auto indexBufferSpecs = IndexBufferSpecs{}; indexBufferSpecs.count = 1; indexBufferSpecs.isDynamic = true; ibo.reset(RenderFactory::makeIndexBuffer(indexBufferSpecs)); @@ -72,9 +77,9 @@ struct Light { auto const model = glm::translate(glm::mat4(1.0F), position); auto const scaleMatrix = glm::scale(glm::mat4(1.0F), {scale, scale, scale}); - for (auto const& vertex : lightMesh_.getVertices()) - { - auto const transformedPos = model * scaleMatrix * glm::vec4(vertex.position, 1.0F); + for (auto const& vertex : lightMesh_.getVertices()) { + auto const transformedPos + = model * scaleMatrix * glm::vec4(vertex.position, 1.0F); vertices.push_back({glm::vec3(transformedPos), color}); } @@ -83,9 +88,14 @@ struct Light shader->setMat4("u_Projection", projection); vao->bind(); - auto const sizeInBytes = static_cast(vertices.size() * sizeof(Light::Vertex)); + auto const sizeInBytes + = static_cast(vertices.size() * sizeof(Light::Vertex)); vbo->uploadData(0, sizeInBytes, vertices.data()); - RenderCommand::drawArrays(RenderDrawMode::Triangles, 0, static_cast(vertices.size())); + RenderCommand::drawArrays( + RenderDrawMode::Triangles, + 0, + static_cast(vertices.size()) + ); // drawStats_.numVertices += vertices.size(); vertices.clear(); vao->unbind(); diff --git a/src/moci/graphics_extra/mesh.cpp b/src/moci/graphics_extra/mesh.cpp index 473a1ca..cdd8659 100644 --- a/src/moci/graphics_extra/mesh.cpp +++ b/src/moci/graphics_extra/mesh.cpp @@ -5,34 +5,38 @@ #include "assimp/postprocess.h" #include "assimp/scene.h" -namespace moci -{ - -namespace -{ -constexpr uint32_t SMeshImportFlags = aiProcess_CalcTangentSpace | // Create binormals/tangents just in case - aiProcess_Triangulate | // Make sure we're triangles - aiProcess_SortByPType | // Split meshes by primitive type - aiProcess_GenNormals | // Make sure we have legit normals - aiProcess_GenUVCoords | // Convert UVs if required - aiProcess_OptimizeMeshes | // Batch draws where possible - aiProcess_ValidateDataStructure; // Validation +namespace moci { + +namespace { +constexpr uint32_t SMeshImportFlags + = aiProcess_CalcTangentSpace | // Create binormals/tangents just in case + aiProcess_Triangulate | // Make sure we're triangles + aiProcess_SortByPType | // Split meshes by primitive type + aiProcess_GenNormals | // Make sure we have legit normals + aiProcess_GenUVCoords | // Convert UVs if required + aiProcess_OptimizeMeshes | // Batch draws where possible + aiProcess_ValidateDataStructure; // Validation struct LogStream : public Assimp::LogStream { static void initialize() { - if (Assimp::DefaultLogger::isNullLogger()) - { + if (Assimp::DefaultLogger::isNullLogger()) { Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE); - Assimp::DefaultLogger::get()->attachStream(new LogStream, Assimp::Logger::Err | Assimp::Logger::Warn); + Assimp::DefaultLogger::get()->attachStream( + new LogStream, + Assimp::Logger::Err | Assimp::Logger::Warn + ); } } - void write(const char* message) override { MOCI_CORE_ERROR("Assimp error: {0}", message); } + void write(char const* message) override + { + MOCI_CORE_ERROR("Assimp error: {0}", message); + } }; -auto aiMatrix4x4ToGlm(const aiMatrix4x4& from) -> glm::mat4 +auto aiMatrix4x4ToGlm(aiMatrix4x4 const& from) -> glm::mat4 { glm::mat4 to; // the a,b,c,d in assimp is the row ; the 1,2,3,4 is the column @@ -54,8 +58,10 @@ Mesh::Mesh(std::string filePath) : _filePath(std::move(filePath)) _importer = std::make_unique(); - const aiScene* scene = _importer->ReadFile(_filePath, SMeshImportFlags); - if ((scene == nullptr) || !scene->HasMeshes()) { MOCI_CORE_ERROR("Failed to load mesh file: {0}", _filePath); } + aiScene const* scene = _importer->ReadFile(_filePath, SMeshImportFlags); + if ((scene == nullptr) || !scene->HasMeshes()) { + MOCI_CORE_ERROR("Failed to load mesh file: {0}", _filePath); + } _isAnimated = scene->mAnimations != nullptr; _inverseTransform = glm::inverse(aiMatrix4x4ToGlm(scene->mRootNode->mTransformation)); @@ -64,11 +70,10 @@ Mesh::Mesh(std::string filePath) : _filePath(std::move(filePath)) uint32_t indexCount = 0; _submeshes.reserve(scene->mNumMeshes); - for (size_t m = 0; m < scene->mNumMeshes; m++) - { + for (size_t m = 0; m < scene->mNumMeshes; m++) { aiMesh* mesh = scene->mMeshes[m]; - Submesh submesh {}; + Submesh submesh{}; submesh.BaseVertex = vertexCount; submesh.BaseIndex = indexCount; submesh.MaterialIndex = mesh->mMaterialIndex; @@ -82,18 +87,18 @@ Mesh::Mesh(std::string filePath) : _filePath(std::move(filePath)) MOCI_CORE_ASSERT(mesh->HasNormals(), "Meshes require normals."); // Vertices - if (not _isAnimated) - { - for (size_t i = 0; i < mesh->mNumVertices; i++) - { + if (not _isAnimated) { + for (size_t i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; - vertex.position = {mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z}; - vertex.normal = {mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z}; - vertex.color = static_cast(moci::Colors::blue); - - if (mesh->HasTextureCoords(0)) - { - vertex.texCoord = {mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y}; + vertex.position + = {mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z}; + vertex.normal + = {mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z}; + vertex.color = static_cast(moci::Colors::blue); + + if (mesh->HasTextureCoords(0)) { + vertex.texCoord + = {mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y}; } _staticVertices.push_back(vertex); @@ -101,10 +106,13 @@ Mesh::Mesh(std::string filePath) : _filePath(std::move(filePath)) } // Indices - for (size_t i = 0; i < mesh->mNumFaces; i++) - { + for (size_t i = 0; i < mesh->mNumFaces; i++) { MOCI_CORE_ASSERT(mesh->mFaces[i].mNumIndices == 3, "Must have 3 indices."); - _indices.push_back({mesh->mFaces[i].mIndices[0], mesh->mFaces[i].mIndices[1], mesh->mFaces[i].mIndices[2]}); + _indices.push_back( + {mesh->mFaces[i].mIndices[0], + mesh->mFaces[i].mIndices[1], + mesh->mFaces[i].mIndices[2]} + ); } } } diff --git a/src/moci/graphics_extra/mesh.hpp b/src/moci/graphics_extra/mesh.hpp index 568db7b..06dd0f3 100644 --- a/src/moci/graphics_extra/mesh.hpp +++ b/src/moci/graphics_extra/mesh.hpp @@ -10,18 +10,17 @@ #include #include -namespace moci -{ +namespace moci { class Mesh { public: struct Vertex { - glm::vec3 position {}; - glm::vec3 normal {}; - glm::vec4 color {}; - glm::vec2 texCoord {}; + glm::vec3 position{}; + glm::vec3 normal{}; + glm::vec4 color{}; + glm::vec2 texCoord{}; }; struct Index @@ -41,16 +40,20 @@ class Mesh }; explicit Mesh(std::string filePath); - [[nodiscard]] auto getVertices() const noexcept -> std::span { return _staticVertices; } + + [[nodiscard]] auto getVertices() const noexcept -> std::span + { + return _staticVertices; + } private: - std::string _filePath {}; - std::unique_ptr _importer {}; - glm::mat4 _inverseTransform {}; - std::vector _submeshes {}; - std::vector _staticVertices {}; + std::string _filePath{}; + std::unique_ptr _importer{}; + glm::mat4 _inverseTransform{}; + std::vector _submeshes{}; + std::vector _staticVertices{}; bool _isAnimated = false; - std::vector _indices {}; + std::vector _indices{}; }; } // namespace moci diff --git a/src/moci/graphics_extra/mesh.test.cpp b/src/moci/graphics_extra/mesh.test.cpp index 459af55..4c3357a 100644 --- a/src/moci/graphics_extra/mesh.test.cpp +++ b/src/moci/graphics_extra/mesh.test.cpp @@ -10,12 +10,12 @@ TEST_CASE("graphics_extra: MeshLoadFromFile", "[graphics]") { SECTION("Cube") { - auto const mesh = moci::Mesh {"moci_test_data/cube.obj"}; + auto const mesh = moci::Mesh{"moci_test_data/cube.obj"}; REQUIRE(mesh.getVertices().size() == 36); } SECTION("Teapot") { - auto const mesh = moci::Mesh {"moci_test_data/teapot.obj"}; + auto const mesh = moci::Mesh{"moci_test_data/teapot.obj"}; REQUIRE(mesh.getVertices().size() == 18960); } } diff --git a/src/moci/graphics_extra/painter.hpp b/src/moci/graphics_extra/painter.hpp index 906e380..431a6b4 100644 --- a/src/moci/graphics_extra/painter.hpp +++ b/src/moci/graphics_extra/painter.hpp @@ -2,7 +2,6 @@ #include "render_queue.hpp" -namespace moci -{ +namespace moci { using Painter = BatchRender2D; } // namespace moci diff --git a/src/moci/graphics_extra/render_queue.cpp b/src/moci/graphics_extra/render_queue.cpp index 6eee6bf..592b445 100644 --- a/src/moci/graphics_extra/render_queue.cpp +++ b/src/moci/graphics_extra/render_queue.cpp @@ -14,8 +14,7 @@ #include -namespace moci -{ +namespace moci { BatchRender2D::BatchRender2D() { @@ -33,13 +32,17 @@ BatchRender2D::BatchRender2D() _data.defaultTexture = moci::RenderFactory::makeTexture2D("assets/white_10x10.png"); moci::BufferLayout layout = { - {moci::ShaderDataType::Float3, "position"}, // - {moci::ShaderDataType::Float4, "color"}, // - {moci::ShaderDataType::Float2, "texture"}, // - {moci::ShaderDataType::Float, "textureIndex"}, // - {moci::ShaderDataType::Float, "textureIsMonochrome"}, // + {moci::ShaderDataType::Float3, "position" }, // + {moci::ShaderDataType::Float4, "color" }, // + {moci::ShaderDataType::Float2, "texture" }, // + {moci::ShaderDataType::Float, "textureIndex" }, // + {moci::ShaderDataType::Float, "textureIsMonochrome"}, // }; - _data.vbo.reset(moci::RenderFactory::makeVertexBuffer(nullptr, sizeof(Vertex) * maxVertexCount, true)); + _data.vbo.reset(moci::RenderFactory::makeVertexBuffer( + nullptr, + sizeof(Vertex) * maxVertexCount, + true + )); _data.vbo->setLayout(layout); _data.vbo->unbind(); _data.ibo.reset(moci::RenderFactory::makeIndexBuffer({{}, maxIndexCount, true})); @@ -68,7 +71,8 @@ auto BatchRender2D::startFrame(float width, float height) -> void _data.shader->bind(); auto const proj = glm::ortho(0.0F, width, height, 0.0F, -1.0F, 1.0F); _data.shader->setMat4("u_MVP", proj); - auto samplers = std::array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + auto samplers + = std::array{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; _data.shader->setInts("u_Textures", (int)samplers.size(), samplers.data()); resetFrameStats(); @@ -83,12 +87,16 @@ auto BatchRender2D::endFrame() -> void _data.shader->unbind(); } -auto BatchRender2D::drawText(const std::string& text, glm::vec2 position, float scale, ColorRGBA32 color) -> void +auto BatchRender2D::drawText( + std::string const& text, + glm::vec2 position, + float scale, + ColorRGBA32 color +) -> void { MOCI_PROFILE_FUNCTION(); - for (auto const c : text) - { + for (auto const c : text) { auto const& ch = _characters[c]; float const xpos = position.x + ch.Bearing.x * scale; @@ -99,25 +107,28 @@ auto BatchRender2D::drawText(const std::string& text, glm::vec2 position, float drawQuad({xpos, ypos - h, w, h}, color, ch.TextureID); // Now advance cursors for next glyph (note that advance is number of 1/64 pixels) - position.x += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64) + position.x += (ch.Advance >> 6) + * scale; // Bitshift by 6 to get value in pixels (2^6 = 64) } } auto BatchRender2D::fontInit(std::string const& fontPath) -> void { FT_Library ft = nullptr; - if (FT_Init_FreeType(&ft) != 0) { MOCI_CORE_ERROR("freetype: Could not init FreeType Library"); } + if (FT_Init_FreeType(&ft) != 0) { + MOCI_CORE_ERROR("freetype: Could not init FreeType Library"); + } FT_Face face = nullptr; - if (FT_New_Face(ft, fontPath.c_str(), 0, &face) != 0) { MOCI_CORE_ERROR("freetype: Failed to load font"); } + if (FT_New_Face(ft, fontPath.c_str(), 0, &face) != 0) { + MOCI_CORE_ERROR("freetype: Failed to load font"); + } FT_Set_Pixel_Sizes(face, 0, 48); - for (std::uint8_t c = 0; c < 128; c++) - { + for (std::uint8_t c = 0; c < 128; c++) { // Load character glyph - if (FT_Load_Char(face, c, FT_LOAD_RENDER) != 0) - { + if (FT_Load_Char(face, c, FT_LOAD_RENDER) != 0) { MOCI_CORE_ERROR("freetype: Failed to load Glyph"); continue; } @@ -161,7 +172,8 @@ auto BatchRender2D::endBatch() -> void { MOCI_PROFILE_FUNCTION(); _data.vao->bind(); - auto const verticesSize = static_cast(_data.vertices.size() * sizeof(Vertex)); + auto const verticesSize + = static_cast(_data.vertices.size() * sizeof(Vertex)); _data.vbo->uploadData(0, verticesSize, _data.vertices.data()); _data.ibo->uploadData(0, _data.indices); _data.vao->unbind(); @@ -170,7 +182,9 @@ auto BatchRender2D::endBatch() -> void auto BatchRender2D::flush() -> void { MOCI_PROFILE_FUNCTION(); - for (size_t i = 0; i < _data.textures.size(); i++) { _data.textures[i]->bind(static_cast(i)); } + for (size_t i = 0; i < _data.textures.size(); i++) { + _data.textures[i]->bind(static_cast(i)); + } _data.vao->bind(); { @@ -180,48 +194,51 @@ auto BatchRender2D::flush() -> void RenderCommand::drawIndexed(mode, numIndices, nullptr); } _data.vao->unbind(); - for (auto const& tex : _data.textures) { tex->unbind(); } + for (auto const& tex : _data.textures) { + tex->unbind(); + } _data.renderFrameStats.drawCount++; } auto BatchRender2D::flushIf(bool shouldFlush) -> void { - if (shouldFlush) - { + if (shouldFlush) { endBatch(); flush(); beginBatch(); } } -auto BatchRender2D::drawQuad(Rectangle rect, ColorRGBA32 color, Texture2D::Optional texture) -> void + +auto BatchRender2D::drawQuad( + Rectangle rect, + ColorRGBA32 color, + Texture2D::Optional texture +) -> void { flushIf(_data.indices.size() + 6 >= maxIndexCount); - int texID {-1}; - if (texture) - { + int texID{-1}; + if (texture) { std::uint32_t counter = 0; - for (auto& tex : _data.textures) - { - if (tex.get() == texture->get()) - { + for (auto& tex : _data.textures) { + if (tex.get() == texture->get()) { texID = counter; break; } counter++; } - if (texID == -1) - { + if (texID == -1) { flushIf(_data.textures.size() == maxTextureUnits); texID = static_cast(_data.textures.size()); _data.textures.push_back(texture.value()); _data.renderFrameStats.textureCount++; } + } else { + texID = 0; } - else { texID = 0; } MOCI_CORE_ASSERT(texID >= 0, ""); @@ -229,36 +246,80 @@ auto BatchRender2D::drawQuad(Rectangle rect, ColorRGBA32 color, Texture2D auto const y = rect.getY(); auto const width = rect.getWidth(); auto const height = rect.getHeight(); - _data.vertices.push_back(Vertex {{x, y, 0.0F}, color, {0.0F, 0.0F}, static_cast(texID), 1.0F}); - _data.vertices.push_back(Vertex {{x + width, y, 0.0F}, color, {1.0F, 0.0F}, static_cast(texID), 1.0F}); - _data.vertices.push_back( - Vertex {{x + width, y + height, 0.0F}, color, {1.0F, 1.0F}, static_cast(texID), 1.0F}); - _data.vertices.push_back(Vertex {{x, y + height, 0.0F}, color, {0.0F, 1.0F}, static_cast(texID), 1.0F}); - - for (auto const i : {0, 1, 2, 2, 3, 0}) { _data.indices.push_back(static_cast(_data.indexOffset + i)); } + _data.vertices.push_back(Vertex{ + {x, y, 0.0F}, + color, + {0.0F, 0.0F}, + static_cast(texID), + 1.0F + }); + _data.vertices.push_back(Vertex{ + {x + width, y, 0.0F}, + color, + {1.0F, 0.0F}, + static_cast(texID), + 1.0F + }); + _data.vertices.push_back(Vertex{ + {x + width, y + height, 0.0F}, + color, + {1.0F, 1.0F}, + static_cast(texID), + 1.0F + }); + _data.vertices.push_back(Vertex{ + {x, y + height, 0.0F}, + color, + {0.0F, 1.0F}, + static_cast(texID), + 1.0F + }); + + for (auto const i : {0, 1, 2, 2, 3, 0}) { + _data.indices.push_back(static_cast(_data.indexOffset + i)); + } _data.indexOffset += 4; _data.renderFrameStats.vertexCount += 4; _data.renderFrameStats.quadCount += 1; } -auto BatchRender2D::drawCircle(float x, float y, float radius, int numSides, ColorRGBA32 color) -> void +auto BatchRender2D::drawCircle( + float x, + float y, + float radius, + int numSides, + ColorRGBA32 color +) -> void { - flushIf(_data.indices.size() + (static_cast(3) * static_cast(numSides)) >= maxIndexCount); + flushIf( + _data.indices.size() + (static_cast(3) * static_cast(numSides)) + >= maxIndexCount + ); auto const numVertices = numSides + 2; auto const doublePI = 3.141F * 2.0F; - _data.vertices.push_back(Vertex {{x, y, 0.0F}, color, {0.0F, 0.0F}, 0.0F}); - for (auto i = 1; i < numVertices; i++) - { - auto const newX = x + (radius * glm::cos(i * doublePI / static_cast(numSides))); - auto const newY = y + (radius * glm::sin(i * doublePI / static_cast(numSides))); - _data.vertices.push_back(Vertex {{newX, newY, 0.0F}, color, {0.0F, 0.0F}, 1.0F}); + _data.vertices.push_back(Vertex{ + {x, y, 0.0F}, + color, + {0.0F, 0.0F}, + 0.0F + }); + for (auto i = 1; i < numVertices; i++) { + auto const newX + = x + (radius * glm::cos(i * doublePI / static_cast(numSides))); + auto const newY + = y + (radius * glm::sin(i * doublePI / static_cast(numSides))); + _data.vertices.push_back(Vertex{ + {newX, newY, 0.0F}, + color, + {0.0F, 0.0F}, + 1.0F + }); } auto const origin = _data.indexOffset; - for (auto i = 0; i < numSides; i++) - { + for (auto i = 0; i < numSides; i++) { _data.indices.push_back(static_cast(origin)); _data.indices.push_back(static_cast(origin + (1 + i))); _data.indices.push_back(static_cast(origin + (2 + i))); @@ -268,7 +329,11 @@ auto BatchRender2D::drawCircle(float x, float y, float radius, int numSides, Col _data.renderFrameStats.vertexCount += numVertices; _data.renderFrameStats.circleCount += 1; } -auto BatchRender2D::getFrameStats() const -> BatchRender2D::FrameStats { return _data.renderFrameStats; } + +auto BatchRender2D::getFrameStats() const -> BatchRender2D::FrameStats +{ + return _data.renderFrameStats; +} auto BatchRender2D::resetFrameStats() -> void { _data.renderFrameStats = {}; } diff --git a/src/moci/graphics_extra/render_queue.hpp b/src/moci/graphics_extra/render_queue.hpp index 9d2d3b7..4ab25ea 100644 --- a/src/moci/graphics_extra/render_queue.hpp +++ b/src/moci/graphics_extra/render_queue.hpp @@ -15,8 +15,7 @@ #include #include -namespace moci -{ +namespace moci { class BatchRender2D { @@ -34,15 +33,22 @@ class BatchRender2D ~BatchRender2D(); // BatchRender2D is not copyable. - BatchRender2D(const BatchRender2D&) = delete; - auto operator=(const BatchRender2D&) -> BatchRender2D& = delete; + BatchRender2D(BatchRender2D const&) = delete; + auto operator=(BatchRender2D const&) -> BatchRender2D& = delete; auto startFrame(float width, float height) -> void; auto endFrame() -> void; - auto drawText(const std::string& text, glm::vec2 position, float scale, ColorRGBA32 color) -> void; - auto drawQuad(Rectangle rect, ColorRGBA32 color, Texture2D::Optional texture = std::nullopt) -> void; - auto drawCircle(float x, float y, float radius, int numSides, ColorRGBA32 color) -> void; + auto + drawText(std::string const& text, glm::vec2 position, float scale, ColorRGBA32 color) + -> void; + auto drawQuad( + Rectangle rect, + ColorRGBA32 color, + Texture2D::Optional texture = std::nullopt + ) -> void; + auto drawCircle(float x, float y, float radius, int numSides, ColorRGBA32 color) + -> void; [[nodiscard]] auto getFrameStats() const -> FrameStats; @@ -63,10 +69,10 @@ class BatchRender2D struct RenderData { - std::shared_ptr vbo = nullptr; - std::shared_ptr ibo = nullptr; - std::shared_ptr vao = nullptr; - std::shared_ptr shader = nullptr; + std::shared_ptr vbo = nullptr; + std::shared_ptr ibo = nullptr; + std::shared_ptr vao = nullptr; + std::shared_ptr shader = nullptr; std::vector vertices = {}; std::vector indices = {}; std::uint32_t indexOffset = 0; @@ -90,7 +96,7 @@ class BatchRender2D auto endBatch() -> void; auto resetFrameStats() -> void; - RenderData _data {}; + RenderData _data{}; std::map _characters; }; diff --git a/src/moci/render/api.hpp b/src/moci/render/api.hpp index afb542a..62e1231 100644 --- a/src/moci/render/api.hpp +++ b/src/moci/render/api.hpp @@ -6,8 +6,7 @@ #include -namespace moci -{ +namespace moci { enum class RenderDrawMode { @@ -38,9 +37,11 @@ class RendererAPI virtual void setClearColor(ColorRGBA32 color) = 0; virtual void clear() = 0; - virtual void drawArrays(RenderDrawMode mode, uint32_t first, uint32_t count) = 0; - virtual void drawIndexed(RenderDrawMode mode, uint32_t count, void* indices) = 0; - virtual void drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) = 0; + virtual void drawArrays(RenderDrawMode mode, uint32_t first, uint32_t count) = 0; + virtual void drawIndexed(RenderDrawMode mode, uint32_t count, void* indices) = 0; + virtual void + drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) + = 0; virtual auto maxTextureSize() -> std::uint32_t = 0; virtual auto maxTextureUnits() -> std::uint32_t = 0; diff --git a/src/moci/render/buffer.hpp b/src/moci/render/buffer.hpp index 2f77fb5..67f23fb 100644 --- a/src/moci/render/buffer.hpp +++ b/src/moci/render/buffer.hpp @@ -8,8 +8,7 @@ #include #include -namespace moci -{ +namespace moci { enum class ShaderDataType { @@ -29,8 +28,7 @@ enum class ShaderDataType static auto shaderDataTypeSize(ShaderDataType type) -> std::uint32_t { - switch (type) - { + switch (type) { case ShaderDataType::Float: return 4; case ShaderDataType::Float2: return 4 * 2; case ShaderDataType::Float3: return 4 * 3; @@ -42,7 +40,9 @@ static auto shaderDataTypeSize(ShaderDataType type) -> std::uint32_t case ShaderDataType::Int3: return 4 * 3; case ShaderDataType::Int4: return 4 * 4; case ShaderDataType::Bool: return 1; - case ShaderDataType::None: MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); return 0; + case ShaderDataType::None: + MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); + return 0; } MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); @@ -54,20 +54,21 @@ struct BufferElement std::string Name; ShaderDataType Type; std::uint32_t Size; - size_t Offset {0}; + size_t Offset{0}; bool Normalized; // BufferElement() = default; BufferElement(ShaderDataType type, std::string name, bool normalized = false) - : Name(std::move(name)), Type(type), Size(shaderDataTypeSize(type)), Normalized(normalized) - { - } + : Name(std::move(name)) + , Type(type) + , Size(shaderDataTypeSize(type)) + , Normalized(normalized) + {} [[nodiscard]] auto getComponentCount() const -> std::uint32_t { - switch (Type) - { + switch (Type) { case ShaderDataType::Float: return 1; case ShaderDataType::Float2: return 2; case ShaderDataType::Float3: return 3; @@ -79,7 +80,9 @@ struct BufferElement case ShaderDataType::Int3: return 3; case ShaderDataType::Int4: return 4; case ShaderDataType::Bool: return 1; - case ShaderDataType::None: MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); return 0; + case ShaderDataType::None: + MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); + return 0; } MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); @@ -91,23 +94,39 @@ class BufferLayout { public: BufferLayout() = default; - BufferLayout(std::initializer_list elements) : _elements(elements) { calculateOffsetsAndStride(); } + + BufferLayout(std::initializer_list elements) : _elements(elements) + { + calculateOffsetsAndStride(); + } [[nodiscard]] inline auto getStride() const -> std::uint32_t { return _stride; } - [[nodiscard]] inline auto getElements() const -> std::vector const& { return _elements; } + + [[nodiscard]] inline auto getElements() const -> std::vector const& + { + return _elements; + } auto begin() -> std::vector::iterator { return _elements.begin(); } + auto end() -> std::vector::iterator { return _elements.end(); } - [[nodiscard]] auto begin() const -> std::vector::const_iterator { return _elements.begin(); } - [[nodiscard]] auto end() const -> std::vector::const_iterator { return _elements.end(); } + + [[nodiscard]] auto begin() const -> std::vector::const_iterator + { + return _elements.begin(); + } + + [[nodiscard]] auto end() const -> std::vector::const_iterator + { + return _elements.end(); + } private: void calculateOffsetsAndStride() { size_t offset = 0; _stride = 0; - for (auto& element : _elements) - { + for (auto& element : _elements) { element.Offset = offset; offset += element.Size; _stride += element.Size; @@ -123,11 +142,13 @@ class VertexBuffer public: virtual ~VertexBuffer() = default; - virtual auto bind() const -> void = 0; - virtual auto unbind() const -> void = 0; - [[nodiscard]] virtual auto getLayout() const -> BufferLayout const& = 0; - virtual auto setLayout(BufferLayout const& layout) -> void = 0; - virtual auto uploadData(std::uint32_t offset, std::uint32_t size, const void* data) const -> void = 0; + virtual auto bind() const -> void = 0; + virtual auto unbind() const -> void = 0; + [[nodiscard]] virtual auto getLayout() const -> BufferLayout const& = 0; + virtual auto setLayout(BufferLayout const& layout) -> void = 0; + virtual auto + uploadData(std::uint32_t offset, std::uint32_t size, void const* data) const -> void + = 0; }; struct IndexBufferSpecs @@ -142,10 +163,12 @@ class IndexBuffer public: virtual ~IndexBuffer() = default; - virtual void bind() const = 0; - virtual void unbind() const = 0; - [[nodiscard]] virtual auto getCount() const -> std::uint32_t = 0; - virtual auto uploadData(std::uint32_t offset, std::span data) const -> void = 0; + virtual void bind() const = 0; + virtual void unbind() const = 0; + [[nodiscard]] virtual auto getCount() const -> std::uint32_t = 0; + virtual auto uploadData(std::uint32_t offset, std::span data) const + -> void + = 0; }; } // namespace moci diff --git a/src/moci/render/buffer.test.cpp b/src/moci/render/buffer.test.cpp index cfebc4a..542b418 100644 --- a/src/moci/render/buffer.test.cpp +++ b/src/moci/render/buffer.test.cpp @@ -8,7 +8,7 @@ TEST_CASE("render/buffer: BufferElement", "[render]") { - moci::BufferElement element {moci::ShaderDataType::Float3, "test"}; + moci::BufferElement element{moci::ShaderDataType::Float3, "test"}; REQUIRE(element.Name == "test"); REQUIRE(element.Size == sizeof(float) * 3); @@ -19,8 +19,8 @@ TEST_CASE("render/buffer: BufferElement", "[render]") TEST_CASE("render/buffer: BufferLayout", "[render]") { moci::BufferLayout layout = { - {moci::ShaderDataType::Float3, "position"}, // - {moci::ShaderDataType::Float4, "color"}, // + {moci::ShaderDataType::Float3, "position"}, // + {moci::ShaderDataType::Float4, "color" }, // }; REQUIRE(layout.getStride() == sizeof(float) * 7); diff --git a/src/moci/render/frame_buffer.hpp b/src/moci/render/frame_buffer.hpp index 882cee2..602489e 100644 --- a/src/moci/render/frame_buffer.hpp +++ b/src/moci/render/frame_buffer.hpp @@ -1,8 +1,8 @@ #pragma once #include -namespace moci -{ + +namespace moci { struct FramebufferSpecs { diff --git a/src/moci/render/graphics_context.hpp b/src/moci/render/graphics_context.hpp index 465676a..9798ddb 100644 --- a/src/moci/render/graphics_context.hpp +++ b/src/moci/render/graphics_context.hpp @@ -1,6 +1,6 @@ #pragma once -namespace moci -{ + +namespace moci { class GraphicsContext { diff --git a/src/moci/render/imgui/imgui.hpp b/src/moci/render/imgui/imgui.hpp index 0cd0a5f..433aad4 100644 --- a/src/moci/render/imgui/imgui.hpp +++ b/src/moci/render/imgui/imgui.hpp @@ -2,12 +2,12 @@ // glew is not needed for opengl es 2.0 #if defined(MOCI_API_OPENGL_ES) -#define GLFW_INCLUDE_ES2 -#define IMGUI_IMPL_OPENGL_ES2 -#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM + #define GLFW_INCLUDE_ES2 + #define IMGUI_IMPL_OPENGL_ES2 + #define IMGUI_IMPL_OPENGL_LOADER_CUSTOM #else -#define IMGUI_IMPL_OPENGL_LOADER_GLEW -#include + #define IMGUI_IMPL_OPENGL_LOADER_GLEW + #include #endif #include diff --git a/src/moci/render/imgui/imgui_layer.cpp b/src/moci/render/imgui/imgui_layer.cpp index 7df9cb9..a95074e 100644 --- a/src/moci/render/imgui/imgui_layer.cpp +++ b/src/moci/render/imgui/imgui_layer.cpp @@ -5,12 +5,11 @@ #include #include -namespace moci -{ +namespace moci { ImGuiLayer::ImGuiLayer() = default; -ImGuiLayer::ImGuiLayer(std::string const& /*unused*/) { } +ImGuiLayer::ImGuiLayer(std::string const& /*unused*/) {} ImGuiLayer::~ImGuiLayer() = default; @@ -59,50 +58,52 @@ void ImGuiLayer::begin() ImGui::NewFrame(); } // Docking - ImGuiWindowFlags windowFlags {}; + ImGuiWindowFlags windowFlags{}; static bool optFullscreenPersistant = true; bool optFullscreen = optFullscreenPersistant; static ImGuiDockNodeFlags dockspaceFlags = ImGuiDockNodeFlags_PassthruCentralNode; - // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, - // because it would be confusing to have two docking targets within each others. + // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not + // dockable into, because it would be confusing to have two docking targets within each + // others. windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; - if (optFullscreen) - { + if (optFullscreen) { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->WorkPos); ImGui::SetNextWindowSize(viewport->WorkSize); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0F); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0F); - windowFlags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize - | ImGuiWindowFlags_NoMove; + windowFlags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse + | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; windowFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } - // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background - // and handle the pass-thru hole, so we ask Begin() to not render a background. - if ((dockspaceFlags & ImGuiDockNodeFlags_PassthruCentralNode) != 0) - { + // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our + // background and handle the pass-thru hole, so we ask Begin() to not render a + // background. + if ((dockspaceFlags & ImGuiDockNodeFlags_PassthruCentralNode) != 0) { windowFlags |= ImGuiWindowFlags_NoBackground; } - // Important: note that we proceed even if Begin() returns false (aka window is collapsed). - // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, - // all active windows docked into it will lose their parent and become undocked. - // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise - // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. + // Important: note that we proceed even if Begin() returns false (aka window is + // collapsed). This is because we want to keep our DockSpace() active. If a DockSpace() + // is inactive, all active windows docked into it will lose their parent and become + // undocked. We cannot preserve the docking relationship between an active window and an + // inactive docking, otherwise any change of dockspace/settings would lead to windows + // being stuck in limbo and never being visible. static auto pOpen = true; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0F, 0.0F)); ImGui::Begin("DockSpace Demo", &pOpen, windowFlags); ImGui::PopStyleVar(); - if (optFullscreen) { ImGui::PopStyleVar(2); } + if (optFullscreen) { + ImGui::PopStyleVar(2); + } // DockSpace ImGuiIO& io = ImGui::GetIO(); - if ((io.ConfigFlags & ImGuiConfigFlags_DockingEnable) != 0) - { + if ((io.ConfigFlags & ImGuiConfigFlags_DockingEnable) != 0) { ImGuiID dockspaceId = ImGui::GetID("dock_space"); ImGui::DockSpace(dockspaceId, ImVec2(0.0F, 0.0F), dockspaceFlags); } @@ -121,5 +122,5 @@ void ImGuiLayer::end() } } -void ImGuiLayer::onImGuiRender() { } +void ImGuiLayer::onImGuiRender() {} } // namespace moci diff --git a/src/moci/render/imgui/imgui_layer.hpp b/src/moci/render/imgui/imgui_layer.hpp index 0b178d4..69bf67e 100644 --- a/src/moci/render/imgui/imgui_layer.hpp +++ b/src/moci/render/imgui/imgui_layer.hpp @@ -4,8 +4,7 @@ #include -namespace moci -{ +namespace moci { class ImGuiLayer : public Layer { diff --git a/src/moci/render/opengl/common/shader_parser.cpp b/src/moci/render/opengl/common/shader_parser.cpp index 29a55fb..ac20e2e 100644 --- a/src/moci/render/opengl/common/shader_parser.cpp +++ b/src/moci/render/opengl/common/shader_parser.cpp @@ -3,16 +3,18 @@ #include #define GL_FRAGMENT_SHADER 0x8B30 -#define GL_VERTEX_SHADER 0x8B31 +#define GL_VERTEX_SHADER 0x8B31 -namespace moci -{ -namespace -{ +namespace moci { +namespace { auto shaderTypeFromString(std::string_view type) -> ShaderType { - if (type == "vertex") { return ShaderType::Vertex; } - if (type == "fragment" || type == "pixel") { return ShaderType::Fragment; } + if (type == "vertex") { + return ShaderType::Vertex; + } + if (type == "fragment" || type == "pixel") { + return ShaderType::Fragment; + } MOCI_CORE_ASSERT(false, "Unknown shader type!"); return ShaderType::Unknown; @@ -24,12 +26,11 @@ auto ShaderParser::splitSource(std::string const& sources) -> ShaderProgramSourc constexpr char const* typeToken = "#type"; auto const typeTokenLength = strlen(typeToken); - auto shaderSources = ShaderProgramSource {}; + auto shaderSources = ShaderProgramSource{}; // Start of shader type declaration line auto pos = sources.find(typeToken, 0); - while (pos != std::string::npos) - { + while (pos != std::string::npos) { // End of shader type declaration line auto const eol = sources.find_first_of("\r\n", pos); MOCI_CORE_ASSERT(eol != std::string::npos, "Syntax error"); @@ -37,7 +38,10 @@ auto ShaderParser::splitSource(std::string const& sources) -> ShaderProgramSourc // Start of shader type name (after "#type " keyword) auto const begin = pos + typeTokenLength + 1; std::string type = sources.substr(begin, eol - begin); - MOCI_CORE_ASSERT(shaderTypeFromString(type) != ShaderType::Unknown, "Invalid shader type specified"); + MOCI_CORE_ASSERT( + shaderTypeFromString(type) != ShaderType::Unknown, + "Invalid shader type specified" + ); // Start of shader code after shader type declaration line auto nextLinePos = sources.find_first_not_of("\r\n", eol); @@ -45,10 +49,13 @@ auto ShaderParser::splitSource(std::string const& sources) -> ShaderProgramSourc // Start of next shader type declaration line pos = sources.find(typeToken, nextLinePos); - auto const source = (pos == std::string::npos) ? sources.substr(nextLinePos) // - : sources.substr(nextLinePos, pos - nextLinePos); + auto const source = (pos == std::string::npos) + ? sources.substr(nextLinePos) // + : sources.substr(nextLinePos, pos - nextLinePos); - shaderSources.shaders.push_back(ShaderStageSource {shaderTypeFromString(type), source}); + shaderSources.shaders.push_back( + ShaderStageSource{shaderTypeFromString(type), source} + ); } return shaderSources; diff --git a/src/moci/render/opengl/common/shader_parser.hpp b/src/moci/render/opengl/common/shader_parser.hpp index 4ea5e27..9bd96a3 100644 --- a/src/moci/render/opengl/common/shader_parser.hpp +++ b/src/moci/render/opengl/common/shader_parser.hpp @@ -2,8 +2,7 @@ #include -namespace moci -{ +namespace moci { class ShaderParser { diff --git a/src/moci/render/opengl/es2/buffer.cpp b/src/moci/render/opengl/es2/buffer.cpp index b545889..1e618e0 100644 --- a/src/moci/render/opengl/es2/buffer.cpp +++ b/src/moci/render/opengl/es2/buffer.cpp @@ -2,8 +2,7 @@ #include -namespace moci -{ +namespace moci { ///////////////////////////////////////////////////////////////////////////// // VertexBuffer ///////////////////////////////////////////////////////////// @@ -14,20 +13,31 @@ OpenGLESVertexBuffer::OpenGLESVertexBuffer(float* vertices, uint32_t size, bool GLCall(glGenBuffers(1, &_rendererID)); GLCall(glBindBuffer(GL_ARRAY_BUFFER, _rendererID)); - if (dynamic) { GLCall(glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW)); } - else { GLCall(glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW)); } + if (dynamic) { + GLCall(glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW)); + } else { + GLCall(glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW)); + } } OpenGLESVertexBuffer::~OpenGLESVertexBuffer() { GLCall(glDeleteBuffers(1, &_rendererID)); } -void OpenGLESVertexBuffer::bind() const { GLCall(glBindBuffer(GL_ARRAY_BUFFER, _rendererID)); } +void OpenGLESVertexBuffer::bind() const +{ + GLCall(glBindBuffer(GL_ARRAY_BUFFER, _rendererID)); +} void OpenGLESVertexBuffer::unbind() const { GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); } -auto OpenGLESVertexBuffer::uploadData(std::uint32_t offset, std::uint32_t size, const void* data) const -> void +auto OpenGLESVertexBuffer::uploadData( + std::uint32_t offset, + std::uint32_t size, + void const* data +) const -> void { GLCall(glBufferSubData(GL_ARRAY_BUFFER, offset, size, data)); } + ///////////////////////////////////////////////////////////////////////////// // IndexBuffer ////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// @@ -39,12 +49,17 @@ OpenGLESIndexBuffer::OpenGLESIndexBuffer(IndexBufferSpecs specs) : _specs(specs) GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _rendererID)); auto const size = _specs.count * sizeof(std::uint16_t); - if (_specs.isDynamic) { GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW)); } - else - { + if (_specs.isDynamic) { + GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW)); + } else { auto indicesShort = convertToUnsignedShorts(_specs.indices); - MOCI_CORE_ASSERT(size == indicesShort.size_bytes(), "Index span size & given size don't match"); - GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, indicesShort.data(), GL_STATIC_DRAW)); + MOCI_CORE_ASSERT( + size == indicesShort.size_bytes(), + "Index span size & given size don't match" + ); + GLCall( + glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, indicesShort.data(), GL_STATIC_DRAW) + ); } unbind(); @@ -52,22 +67,32 @@ OpenGLESIndexBuffer::OpenGLESIndexBuffer(IndexBufferSpecs specs) : _specs(specs) OpenGLESIndexBuffer::~OpenGLESIndexBuffer() { GLCall(glDeleteBuffers(1, &_rendererID)); } -void OpenGLESIndexBuffer::bind() const { GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _rendererID)); } +void OpenGLESIndexBuffer::bind() const +{ + GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _rendererID)); +} -void OpenGLESIndexBuffer::unbind() const { GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); } +void OpenGLESIndexBuffer::unbind() const +{ + GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); +} -auto OpenGLESIndexBuffer::uploadData(std::uint32_t offset, std::span indices) const -> void +auto OpenGLESIndexBuffer::uploadData(std::uint32_t offset, std::span indices) + const -> void { auto indicesShort = convertToUnsignedShorts(indices); auto const size = indicesShort.size() * sizeof(std::uint16_t); GLCall(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, size, indicesShort.data())); } -auto OpenGLESIndexBuffer::convertToUnsignedShorts(std::span indices) const -> std::span +auto OpenGLESIndexBuffer::convertToUnsignedShorts(std::span indices) const + -> std::span { _indicesShort->clear(); _indicesShort->reserve(indices.size()); - for (auto const index : indices) { _indicesShort->push_back(static_cast(index)); } + for (auto const index : indices) { + _indicesShort->push_back(static_cast(index)); + } return *_indicesShort; } diff --git a/src/moci/render/opengl/es2/buffer.hpp b/src/moci/render/opengl/es2/buffer.hpp index 12c1a13..f6ebeb8 100644 --- a/src/moci/render/opengl/es2/buffer.hpp +++ b/src/moci/render/opengl/es2/buffer.hpp @@ -5,8 +5,7 @@ #include #include -namespace moci -{ +namespace moci { class OpenGLESVertexBuffer : public VertexBuffer { @@ -16,12 +15,15 @@ class OpenGLESVertexBuffer : public VertexBuffer void bind() const override; void unbind() const override; - auto uploadData(std::uint32_t offset, std::uint32_t size, const void* data) const -> void override; - [[nodiscard]] auto getLayout() const -> const BufferLayout& override { return _layout; } - void setLayout(const BufferLayout& layout) override { _layout = layout; } + auto uploadData(std::uint32_t offset, std::uint32_t size, void const* data) const + -> void override; + + [[nodiscard]] auto getLayout() const -> BufferLayout const& override { return _layout; } + + void setLayout(BufferLayout const& layout) override { _layout = layout; } private: - uint32_t _rendererID {}; + uint32_t _rendererID{}; BufferLayout _layout; }; @@ -33,15 +35,19 @@ class OpenGLESIndexBuffer : public IndexBuffer void bind() const override; void unbind() const override; - auto uploadData(std::uint32_t offset, std::span indices) const -> void override; + auto uploadData(std::uint32_t offset, std::span indices) const + -> void override; + [[nodiscard]] auto getCount() const -> uint32_t override { return _specs.count; } private: - [[nodiscard]] auto convertToUnsignedShorts(std::span indices) const -> std::span; + [[nodiscard]] auto convertToUnsignedShorts(std::span indices) const + -> std::span; - IndexBufferSpecs _specs = {}; - uint32_t _rendererID = {}; - std::unique_ptr> _indicesShort = std::make_unique>(); + IndexBufferSpecs _specs = {}; + uint32_t _rendererID = {}; + std::unique_ptr> _indicesShort + = std::make_unique>(); }; } // namespace moci diff --git a/src/moci/render/opengl/es2/es2.cpp b/src/moci/render/opengl/es2/es2.cpp index e314724..d864e7f 100644 --- a/src/moci/render/opengl/es2/es2.cpp +++ b/src/moci/render/opengl/es2/es2.cpp @@ -2,13 +2,14 @@ void glClearError() { - while (glGetError() != GL_NO_ERROR) { ; } + while (glGetError() != GL_NO_ERROR) { + ; + } } -auto glLogCall(const char* function, const char* file, int line) -> bool +auto glLogCall(char const* function, char const* file, int line) -> bool { - while (GLenum error = glGetError()) - { + while (GLenum error = glGetError()) { MOCI_CORE_ERROR("[OpenGL Error] ({0}): {1} {2}:{3}", error, function, file, line); return false; } diff --git a/src/moci/render/opengl/es2/es2.hpp b/src/moci/render/opengl/es2/es2.hpp index 0ed7a28..dfe6ed7 100644 --- a/src/moci/render/opengl/es2/es2.hpp +++ b/src/moci/render/opengl/es2/es2.hpp @@ -6,27 +6,27 @@ // glfw use gles headers #if defined(MOCI_API_OPENGL_ES) -#define GLFW_INCLUDE_ES2 + #define GLFW_INCLUDE_ES2 #endif // macOS 10.14 deprecated warnings #if defined(MOCI_MAC) -#if not defined(GL_SILENCE_DEPRECATION) -#define GL_SILENCE_DEPRECATION -#endif + #if not defined(GL_SILENCE_DEPRECATION) + #define GL_SILENCE_DEPRECATION + #endif #endif // glew is not needed for opengl es 2.0 or on macOS #if not defined(MOCI_API_OPENGL_ES) -#include + #include #endif #include -#define GLCall(x) \ - glClearError(); \ - x; \ +#define GLCall(x) \ + glClearError(); \ + x; \ glLogCall(#x, __FILE__, __LINE__) void glClearError(); -auto glLogCall(const char* function, const char* file, int line) -> bool; +auto glLogCall(char const* function, char const* file, int line) -> bool; diff --git a/src/moci/render/opengl/es2/frame_buffer.cpp b/src/moci/render/opengl/es2/frame_buffer.cpp index a3917ac..62942af 100644 --- a/src/moci/render/opengl/es2/frame_buffer.cpp +++ b/src/moci/render/opengl/es2/frame_buffer.cpp @@ -2,10 +2,12 @@ #include "es2.hpp" -namespace moci -{ +namespace moci { -OpenGLESFramebuffer::OpenGLESFramebuffer(FramebufferSpecs spec) : _specs(spec) { invalidate(); } +OpenGLESFramebuffer::OpenGLESFramebuffer(FramebufferSpecs spec) : _specs(spec) +{ + invalidate(); +} OpenGLESFramebuffer::~OpenGLESFramebuffer() { deallocate(); } @@ -26,21 +28,43 @@ void OpenGLESFramebuffer::resize(std::uint32_t width, std::uint32_t height) void OpenGLESFramebuffer::invalidate() { - if (_renderID != 0) { deallocate(); } + if (_renderID != 0) { + deallocate(); + } GLCall(glGenFramebuffers(1, &_renderID)); GLCall(glBindFramebuffer(GL_FRAMEBUFFER, _renderID)); GLCall(glGenTextures(1, &_colorAttachment)); GLCall(glBindTexture(GL_TEXTURE_2D, _colorAttachment)); - GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _specs.width, _specs.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr)); + GLCall(glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA, + _specs.width, + _specs.height, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + nullptr + )); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); - GLCall(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _colorAttachment, 0)); + GLCall(glFramebufferTexture2D( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + _colorAttachment, + 0 + )); - MOCI_CORE_ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Framebuffer is incomplete!"); + MOCI_CORE_ASSERT( + glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, + "Framebuffer is incomplete!" + ); glBindFramebuffer(GL_FRAMEBUFFER, 0); } + void OpenGLESFramebuffer::deallocate() { GLCall(glDeleteFramebuffers(1, &_renderID)); diff --git a/src/moci/render/opengl/es2/frame_buffer.hpp b/src/moci/render/opengl/es2/frame_buffer.hpp index d5c894a..f92d71c 100644 --- a/src/moci/render/opengl/es2/frame_buffer.hpp +++ b/src/moci/render/opengl/es2/frame_buffer.hpp @@ -3,8 +3,7 @@ #include -namespace moci -{ +namespace moci { class OpenGLESFramebuffer : public Framebuffer { @@ -17,8 +16,15 @@ class OpenGLESFramebuffer : public Framebuffer void resize(std::uint32_t width, std::uint32_t height) override; - [[nodiscard]] auto getColorAttachmentRendererId() const -> std::uint32_t override { return _colorAttachment; } - [[nodiscard]] auto getSpecification() const -> const FramebufferSpecs& override { return _specs; } + [[nodiscard]] auto getColorAttachmentRendererId() const -> std::uint32_t override + { + return _colorAttachment; + } + + [[nodiscard]] auto getSpecification() const -> FramebufferSpecs const& override + { + return _specs; + } private: void invalidate(); diff --git a/src/moci/render/opengl/es2/graphics_context.cpp b/src/moci/render/opengl/es2/graphics_context.cpp index edf38f3..2807f21 100644 --- a/src/moci/render/opengl/es2/graphics_context.cpp +++ b/src/moci/render/opengl/es2/graphics_context.cpp @@ -3,8 +3,7 @@ #include #include -namespace moci -{ +namespace moci { #if defined(MOCI_API_OPENGL_LEGACY) auto GraphicsContext::create(void* win) -> GraphicsContext* @@ -23,7 +22,9 @@ void OpenGLESContext::init() glfwMakeContextCurrent(_windowHandle); #if not defined(MOCI_API_OPENGL_ES) - if (auto err = glewInit() != GLEW_OK; err) { MOCI_CORE_ASSERT(err, "Failed to initialize glew!"); } + if (auto err = glewInit() != GLEW_OK; err) { + MOCI_CORE_ASSERT(err, "Failed to initialize glew!"); + } #endif // msaa @@ -35,9 +36,18 @@ void OpenGLESContext::init() // Enable depth test MOCI_CORE_INFO("OpenGL Info:"); - MOCI_CORE_INFO(" Vendor: {0}", std::string_view {reinterpret_cast(glGetString(GL_VENDOR))}); - MOCI_CORE_INFO(" Renderer: {0}", std::string_view {reinterpret_cast(glGetString(GL_RENDERER))}); - MOCI_CORE_INFO(" Version: {0}", std::string_view {reinterpret_cast(glGetString(GL_VERSION))}); + MOCI_CORE_INFO( + " Vendor: {0}", + std::string_view{reinterpret_cast(glGetString(GL_VENDOR))} + ); + MOCI_CORE_INFO( + " Renderer: {0}", + std::string_view{reinterpret_cast(glGetString(GL_RENDERER))} + ); + MOCI_CORE_INFO( + " Version: {0}", + std::string_view{reinterpret_cast(glGetString(GL_VERSION))} + ); } void OpenGLESContext::swapBuffers() { glfwSwapBuffers(_windowHandle); } diff --git a/src/moci/render/opengl/es2/graphics_context.hpp b/src/moci/render/opengl/es2/graphics_context.hpp index 8f23b5a..799f706 100644 --- a/src/moci/render/opengl/es2/graphics_context.hpp +++ b/src/moci/render/opengl/es2/graphics_context.hpp @@ -3,8 +3,8 @@ #include struct GLFWwindow; -namespace moci -{ + +namespace moci { class OpenGLESContext : public GraphicsContext { diff --git a/src/moci/render/opengl/es2/renderer_api.cpp b/src/moci/render/opengl/es2/renderer_api.cpp index 2c0e927..0a5a3ee 100644 --- a/src/moci/render/opengl/es2/renderer_api.cpp +++ b/src/moci/render/opengl/es2/renderer_api.cpp @@ -2,50 +2,38 @@ #include -namespace moci -{ -namespace -{ +namespace moci { +namespace { auto mociToOpenGlDrawMode(RenderDrawMode const mode) noexcept -> int { - switch (mode) - { - case RenderDrawMode::None: - { + switch (mode) { + case RenderDrawMode::None: { MOCI_CORE_ERROR("draw mode 'None' not supported"); break; } - case RenderDrawMode::Points: - { + case RenderDrawMode::Points: { return GL_POINTS; } - case RenderDrawMode::LineStrip: - { + case RenderDrawMode::LineStrip: { return GL_LINE_STRIP; } - case RenderDrawMode::LineLoop: - { + case RenderDrawMode::LineLoop: { return GL_LINE_LOOP; } - case RenderDrawMode::Lines: - { + case RenderDrawMode::Lines: { return GL_LINES; } - case RenderDrawMode::TriangleStrips: - { + case RenderDrawMode::TriangleStrips: { return GL_TRIANGLE_STRIP; } - case RenderDrawMode::TriangleFan: - { + case RenderDrawMode::TriangleFan: { return GL_TRIANGLE_FAN; } - case RenderDrawMode::Triangles: - { + case RenderDrawMode::Triangles: { return GL_TRIANGLES; } - default: - { + default: { break; } } @@ -80,22 +68,38 @@ void OpenGLESRendererAPI::setClearColor(ColorRGBA32 color) void OpenGLESRendererAPI::clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } -void OpenGLESRendererAPI::drawArrays(RenderDrawMode const mode, uint32_t first, uint32_t count) +void OpenGLESRendererAPI::drawArrays( + RenderDrawMode const mode, + uint32_t first, + uint32_t count +) { auto const openGLMode = mociToOpenGlDrawMode(mode); GLCall(glDrawArrays(openGLMode, first, count)); } -void OpenGLESRendererAPI::drawIndexed(RenderDrawMode const mode, uint32_t count, void* indices) +void OpenGLESRendererAPI::drawIndexed( + RenderDrawMode const mode, + uint32_t count, + void* indices +) { auto const openGLMode = mociToOpenGlDrawMode(mode); GLCall(glDrawElements(openGLMode, count, GL_UNSIGNED_SHORT, indices)); } -void OpenGLESRendererAPI::drawIndexed(RenderDrawMode const mode, std::shared_ptr const& vertexArray) +void OpenGLESRendererAPI::drawIndexed( + RenderDrawMode const mode, + std::shared_ptr const& vertexArray +) { auto const openGLMode = mociToOpenGlDrawMode(mode); - GLCall(glDrawElements(openGLMode, vertexArray->getIndexBuffer()->getCount(), GL_UNSIGNED_SHORT, nullptr)); + GLCall(glDrawElements( + openGLMode, + vertexArray->getIndexBuffer()->getCount(), + GL_UNSIGNED_SHORT, + nullptr + )); } auto OpenGLESRendererAPI::maxTextureSize() -> std::uint32_t @@ -104,12 +108,14 @@ auto OpenGLESRendererAPI::maxTextureSize() -> std::uint32_t GLCall(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize)); return static_cast(maxTextureSize); } + auto OpenGLESRendererAPI::maxTextureUnits() -> std::uint32_t { GLint maxTextureUnits = 0; GLCall(glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &maxTextureUnits)); return static_cast(maxTextureUnits); } + auto OpenGLESRendererAPI::maxVertexAttributes() -> std::uint32_t { GLint maxAttributes = 0; diff --git a/src/moci/render/opengl/es2/renderer_api.hpp b/src/moci/render/opengl/es2/renderer_api.hpp index 618bbba..501bf09 100644 --- a/src/moci/render/opengl/es2/renderer_api.hpp +++ b/src/moci/render/opengl/es2/renderer_api.hpp @@ -5,8 +5,7 @@ #include -namespace moci -{ +namespace moci { class OpenGLESRendererAPI : public RendererAPI { public: @@ -19,7 +18,8 @@ class OpenGLESRendererAPI : public RendererAPI void drawArrays(RenderDrawMode mode, uint32_t first, uint32_t count) override; void drawIndexed(RenderDrawMode mode, uint32_t count, void* indices) override; - void drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) override; + void drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) + override; auto maxTextureSize() -> std::uint32_t override; auto maxTextureUnits() -> std::uint32_t override; diff --git a/src/moci/render/opengl/es2/shader.cpp b/src/moci/render/opengl/es2/shader.cpp index d97ad02..ee57d1e 100644 --- a/src/moci/render/opengl/es2/shader.cpp +++ b/src/moci/render/opengl/es2/shader.cpp @@ -9,10 +9,8 @@ #include #include -namespace moci -{ -namespace -{ +namespace moci { +namespace { struct ShaderAttribute { std::uint32_t index; @@ -20,23 +18,23 @@ struct ShaderAttribute std::string type; }; -auto getAttributeLayout(const std::string& src) -> std::vector +auto getAttributeLayout(std::string const& src) -> std::vector { std::istringstream f(src); auto result = std::vector(); std::string line; - while (std::getline(f, line)) - { + while (std::getline(f, line)) { auto const found = line.find("attribute"); - if (found != std::string::npos) - { + if (found != std::string::npos) { moci::Strings::trim(line); auto splits = moci::Strings::split(line, ' '); assert(splits.size() == 3); auto type = splits[1]; auto name = splits[2]; - name.erase(std::find_if(name.begin(), name.end(), [](auto ch) { return ch == ';'; })); + name.erase(std::find_if(name.begin(), name.end(), [](auto ch) { + return ch == ';'; + })); result.push_back({static_cast(result.size()), name, type}); } } @@ -53,19 +51,22 @@ OpenGLESShader::OpenGLESShader(std::string const& filepath) _rendererID = createShader(vertex.source.c_str(), fragment.source.c_str()); } -OpenGLESShader::OpenGLESShader(std::string name, std::string const& vertexSrc, std::string const& fragmentSrc) - : _rendererID(createShader(vertexSrc.c_str(), fragmentSrc.c_str())), _name(std::move(name)) -{ -} +OpenGLESShader::OpenGLESShader( + std::string name, + std::string const& vertexSrc, + std::string const& fragmentSrc +) + : _rendererID(createShader(vertexSrc.c_str(), fragmentSrc.c_str())) + , _name(std::move(name)) +{} OpenGLESShader::~OpenGLESShader() { GLCall(glDeleteProgram(_rendererID)); } auto OpenGLESShader::parseShader(std::string const& filepath) -> ShaderProgramSource { std::ifstream file(filepath); - if (file) - { - auto ss = std::ostringstream {}; + if (file) { + auto ss = std::ostringstream{}; ss << file.rdbuf(); auto program = ShaderParser::splitSource(ss.str()); return program; @@ -74,7 +75,8 @@ auto OpenGLESShader::parseShader(std::string const& filepath) -> ShaderProgramSo return {}; } -auto OpenGLESShader::createShader(const char* vertexSource, const char* fragmentSource) -> GLint +auto OpenGLESShader::createShader(char const* vertexSource, char const* fragmentSource) + -> GLint { constexpr auto infoLogLength = 512; GLchar infoLog[infoLogLength]; @@ -86,8 +88,7 @@ auto OpenGLESShader::createShader(const char* vertexSource, const char* fragment GLCall(glShaderSource(vertexShader, 1, &vertexSource, nullptr)); GLCall(glCompileShader(vertexShader)); GLCall(glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success)); - if (success == 0) - { + if (success == 0) { GLCall(glGetShaderInfoLog(vertexShader, infoLogLength, nullptr, infoLog)); MOCI_CORE_ERROR("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n{}\n", infoLog); } @@ -98,8 +99,7 @@ auto OpenGLESShader::createShader(const char* vertexSource, const char* fragment GLCall(glShaderSource(fragmentShader, 1, &fragmentSource, nullptr)); GLCall(glCompileShader(fragmentShader)); GLCall(glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success)); - if (success == 0) - { + if (success == 0) { GLCall(glGetShaderInfoLog(fragmentShader, infoLogLength, nullptr, infoLog)); MOCI_CORE_ERROR("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n{}\n", infoLog); } @@ -112,16 +112,14 @@ auto OpenGLESShader::createShader(const char* vertexSource, const char* fragment // Bind attributes auto const attributes = getAttributeLayout(vertexSource); - for (auto const& a : attributes) - { + for (auto const& a : attributes) { GLCall(glBindAttribLocation(shaderProgram, a.index, a.name.c_str())); MOCI_CORE_INFO("Binding attribute {}: \"{}\"", a.index, a.name); } GLCall(glLinkProgram(shaderProgram)); GLCall(glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success)); - if (success == 0) - { + if (success == 0) { GLCall(glGetProgramInfoLog(shaderProgram, infoLogLength, nullptr, infoLog)); MOCI_CORE_ERROR("ERROR::SHADER::PROGRAM::LINKING_FAILED\n{}\n", infoLog); } @@ -135,7 +133,10 @@ void OpenGLESShader::bind() const { GLCall(glUseProgram(_rendererID)); } void OpenGLESShader::unbind() const { GLCall(glUseProgram(0)); } -void OpenGLESShader::setInt(std::string const& name, int value) { uploadUniformInt(name, value); } +void OpenGLESShader::setInt(std::string const& name, int value) +{ + uploadUniformInt(name, value); +} void OpenGLESShader::setInts(std::string const& name, int count, int* values) { @@ -143,17 +144,35 @@ void OpenGLESShader::setInts(std::string const& name, int count, int* values) uploadUniformInts(name, count, values); } -void OpenGLESShader::setFloat(std::string const& name, float const value) { uploadUniformFloat(name, value); } +void OpenGLESShader::setFloat(std::string const& name, float const value) +{ + uploadUniformFloat(name, value); +} -void OpenGLESShader::setFloat2(std::string const& name, const glm::vec2& value) { uploadUniformFloat2(name, value); } +void OpenGLESShader::setFloat2(std::string const& name, glm::vec2 const& value) +{ + uploadUniformFloat2(name, value); +} -void OpenGLESShader::setFloat3(std::string const& name, const glm::vec3& value) { uploadUniformFloat3(name, value); } +void OpenGLESShader::setFloat3(std::string const& name, glm::vec3 const& value) +{ + uploadUniformFloat3(name, value); +} -void OpenGLESShader::setFloat4(std::string const& name, const glm::vec4& value) { uploadUniformFloat4(name, value); } +void OpenGLESShader::setFloat4(std::string const& name, glm::vec4 const& value) +{ + uploadUniformFloat4(name, value); +} -void OpenGLESShader::setMat3(std::string const& name, const glm::mat3& value) { uploadUniformMat3(name, value); } +void OpenGLESShader::setMat3(std::string const& name, glm::mat3 const& value) +{ + uploadUniformMat3(name, value); +} -void OpenGLESShader::setMat4(std::string const& name, const glm::mat4& value) { uploadUniformMat4(name, value); } +void OpenGLESShader::setMat4(std::string const& name, glm::mat4 const& value) +{ + uploadUniformMat4(name, value); +} auto OpenGLESShader::getLocation(std::string const& name) const -> std::int32_t { @@ -165,7 +184,8 @@ void OpenGLESShader::uploadUniformInt(std::string const& name, int value) const GLCall(glUniform1i(getLocation(name), value)); } -void OpenGLESShader::uploadUniformInts(std::string const& name, int count, int* values) const +void OpenGLESShader::uploadUniformInts(std::string const& name, int count, int* values) + const { GLCall(glUniform1iv(getLocation(name), count, values)); } @@ -175,27 +195,32 @@ void OpenGLESShader::uploadUniformFloat(std::string const& name, float value) co GLCall(glUniform1f(getLocation(name), value)); } -void OpenGLESShader::uploadUniformFloat2(std::string const& name, const glm::vec2& value) const +void OpenGLESShader::uploadUniformFloat2(std::string const& name, glm::vec2 const& value) + const { GLCall(glUniform2f(getLocation(name), value.x, value.y)); } -void OpenGLESShader::uploadUniformFloat3(std::string const& name, const glm::vec3& value) const +void OpenGLESShader::uploadUniformFloat3(std::string const& name, glm::vec3 const& value) + const { GLCall(glUniform3f(getLocation(name), value.x, value.y, value.z)); } -void OpenGLESShader::uploadUniformFloat4(std::string const& name, const glm::vec4& value) const +void OpenGLESShader::uploadUniformFloat4(std::string const& name, glm::vec4 const& value) + const { GLCall(glUniform4f(getLocation(name), value.x, value.y, value.z, value.w)); } -void OpenGLESShader::uploadUniformMat3(std::string const& name, const glm::mat3& matrix) const +void OpenGLESShader::uploadUniformMat3(std::string const& name, glm::mat3 const& matrix) + const { GLCall(glUniformMatrix3fv(getLocation(name), 1, GL_FALSE, glm::value_ptr(matrix))); } -void OpenGLESShader::uploadUniformMat4(std::string const& name, const glm::mat4& matrix) const +void OpenGLESShader::uploadUniformMat4(std::string const& name, glm::mat4 const& matrix) + const { GLCall(glUniformMatrix4fv(getLocation(name), 1, GL_FALSE, glm::value_ptr(matrix))); } diff --git a/src/moci/render/opengl/es2/shader.hpp b/src/moci/render/opengl/es2/shader.hpp index c545682..587b244 100644 --- a/src/moci/render/opengl/es2/shader.hpp +++ b/src/moci/render/opengl/es2/shader.hpp @@ -11,14 +11,17 @@ // TODO: REMOVE! using GLenum = unsigned int; -namespace moci -{ +namespace moci { class OpenGLESShader : public Shader { public: explicit OpenGLESShader(std::string const& filepath); - OpenGLESShader(std::string name, std::string const& vertexSrc, std::string const& fragmentSrc); + OpenGLESShader( + std::string name, + std::string const& vertexSrc, + std::string const& fragmentSrc + ); ~OpenGLESShader() override; void bind() const override; @@ -41,14 +44,14 @@ class OpenGLESShader : public Shader void uploadUniformInt(std::string const& name, int value) const; void uploadUniformInts(std::string const& name, int count, int* values) const; void uploadUniformFloat(std::string const& name, float value) const; - void uploadUniformFloat2(std::string const& name, const glm::vec2& value) const; - void uploadUniformFloat3(std::string const& name, const glm::vec3& value) const; + void uploadUniformFloat2(std::string const& name, glm::vec2 const& value) const; + void uploadUniformFloat3(std::string const& name, glm::vec3 const& value) const; void uploadUniformFloat4(std::string const& name, glm::vec4 const& value) const; void uploadUniformMat3(std::string const& name, glm::mat3 const& matrix) const; void uploadUniformMat4(std::string const& name, glm::mat4 const& matrix) const; - static auto createShader(const char* vertexSource, const char* fragmentSource) -> GLint; + static auto createShader(char const* vertexSource, char const* fragmentSource) -> GLint; static auto parseShader(std::string const& filepath) -> ShaderProgramSource; uint32_t _rendererID; diff --git a/src/moci/render/opengl/es2/texture.cpp b/src/moci/render/opengl/es2/texture.cpp index f1ecb72..bdacd90 100644 --- a/src/moci/render/opengl/es2/texture.cpp +++ b/src/moci/render/opengl/es2/texture.cpp @@ -9,23 +9,41 @@ #include -namespace moci -{ +namespace moci { OpenGLESTexture2D::OpenGLESTexture2D(std::string path) : _path(std::move(path)) { stbi_set_flip_vertically_on_load(1); _data = stbi_load(_path.c_str(), &_width, &_height, &_bpp, 4); - if (_data == nullptr) { MOCI_CORE_ERROR("stbi error"); } + if (_data == nullptr) { + MOCI_CORE_ERROR("stbi error"); + } createTexture(); setFilterModes(); - GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _data)); - - if (_data != nullptr) { stbi_image_free(_data); } + GLCall(glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA, + _width, + _height, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + _data + )); + + if (_data != nullptr) { + stbi_image_free(_data); + } } -OpenGLESTexture2D::OpenGLESTexture2D(Texture::Format format, uint32_t width, uint32_t height, void* data) +OpenGLESTexture2D::OpenGLESTexture2D( + Texture::Format format, + uint32_t width, + uint32_t height, + void* data +) { ignoreUnused(format); createTexture(); @@ -43,7 +61,7 @@ OpenGLESTexture2D::OpenGLESTexture2D(Texture::Format format, uint32_t width, uin GL_LUMINANCE, // GL_UNSIGNED_BYTE, // data // - ) // + ) // ); } @@ -68,6 +86,7 @@ void OpenGLESTexture2D::createTexture() GLCall(glGenTextures(1, &_renderID)); GLCall(glBindTexture(GL_TEXTURE_2D, _renderID)); } + void OpenGLESTexture2D::setFilterModes() { GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); @@ -77,7 +96,8 @@ void OpenGLESTexture2D::setFilterModes() GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); } -OpenGLESTextureCube::OpenGLESTextureCube(std::vector paths) : _paths(std::move(paths)) +OpenGLESTextureCube::OpenGLESTextureCube(std::vector paths) + : _paths(std::move(paths)) { // Generate a texture object @@ -92,39 +112,84 @@ OpenGLESTextureCube::OpenGLESTextureCube(std::vector paths) : _path GLCall(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); GLCall(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); - for (GLuint i = 0; i < _paths.size(); i++) - { + for (GLuint i = 0; i < _paths.size(); i++) { int width = 0; int height = 0; int numChannels = 0; auto* data = stbi_load(_paths[i].c_str(), &width, &height, &numChannels, 0); - if (data != nullptr) - { + if (data != nullptr) { MOCI_CORE_INFO("stbi loaded: {} {}x{}", _paths[i].c_str(), width, height); auto const pos = GL_TEXTURE_CUBE_MAP_POSITIVE_X + i; // Resize on ARM devices with little VRAM. (RPi3 for example) #if defined(MOCI_ARM) - if (width > 1024) - { + if (width > 1024) { auto const newSize = 1024; - MOCI_CORE_INFO(" stbi resize: FROM: {}x{} TO: {}x{}", width, height, newSize, newSize); - std::vector outBuffer {}; + MOCI_CORE_INFO( + " stbi resize: FROM: {}x{} TO: {}x{}", + width, + height, + newSize, + newSize + ); + std::vector outBuffer{}; outBuffer.resize(newSize * newSize * numChannels); - if (stbir_resize_uint8(data, width, height, 0, outBuffer.data(), newSize, newSize, 0, numChannels) == 0) - { + if (stbir_resize_uint8( + data, + width, + height, + 0, + outBuffer.data(), + newSize, + newSize, + 0, + numChannels + ) + == 0) { MOCI_ERROR(" stbi resize error"); } - GLCall(glTexImage2D(pos, 0, GL_RGB, newSize, newSize, 0, GL_RGB, GL_UNSIGNED_BYTE, outBuffer.data())); + GLCall(glTexImage2D( + pos, + 0, + GL_RGB, + newSize, + newSize, + 0, + GL_RGB, + GL_UNSIGNED_BYTE, + outBuffer.data() + )); + } else { + GLCall(glTexImage2D( + pos, + 0, + GL_RGB, + width, + height, + 0, + GL_RGB, + GL_UNSIGNED_BYTE, + data + )); } - else { GLCall(glTexImage2D(pos, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data)); } #else - GLCall(glTexImage2D(pos, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data)); + GLCall(glTexImage2D( + pos, + 0, + GL_RGB, + width, + height, + 0, + GL_RGB, + GL_UNSIGNED_BYTE, + data + )); #endif + } else { + MOCI_CORE_ERROR("stbi error: {}", _paths[i]); } - else { MOCI_CORE_ERROR("stbi error: {}", _paths[i]); } stbi_image_free(data); } diff --git a/src/moci/render/opengl/es2/texture.hpp b/src/moci/render/opengl/es2/texture.hpp index 0c80dcc..3949b81 100644 --- a/src/moci/render/opengl/es2/texture.hpp +++ b/src/moci/render/opengl/es2/texture.hpp @@ -2,21 +2,27 @@ #include -namespace moci -{ +namespace moci { class OpenGLESTexture2D : public Texture2D { public: explicit OpenGLESTexture2D(std::string path); - OpenGLESTexture2D(Texture::Format format, std::uint32_t width, std::uint32_t height, void* data); + OpenGLESTexture2D( + Texture::Format format, + std::uint32_t width, + std::uint32_t height, + void* data + ); ~OpenGLESTexture2D() override; - OpenGLESTexture2D(const OpenGLESTexture2D&) = delete; - auto operator=(const OpenGLESTexture2D&) -> OpenGLESTexture2D& = delete; + OpenGLESTexture2D(OpenGLESTexture2D const&) = delete; + auto operator=(OpenGLESTexture2D const&) -> OpenGLESTexture2D& = delete; [[nodiscard]] auto getWidth() const -> std::uint32_t override { return _width; } + [[nodiscard]] auto getHeight() const -> std::uint32_t override { return _height; } + [[nodiscard]] auto getId() const -> std::uint32_t override { return _renderID; } void bind(std::uint32_t slot = 0) const override; @@ -39,13 +45,15 @@ class OpenGLESTextureCube : public TextureCube public: explicit OpenGLESTextureCube(std::vector paths); - OpenGLESTextureCube(const OpenGLESTextureCube&) = delete; - auto operator=(const OpenGLESTextureCube&) -> OpenGLESTextureCube& = delete; + OpenGLESTextureCube(OpenGLESTextureCube const&) = delete; + auto operator=(OpenGLESTextureCube const&) -> OpenGLESTextureCube& = delete; ~OpenGLESTextureCube() override; [[nodiscard]] auto getWidth() const -> std::uint32_t override { return 0; } + [[nodiscard]] auto getHeight() const -> std::uint32_t override { return 0; } + [[nodiscard]] auto getId() const -> std::uint32_t override { return _renderID; } void bind(std::uint32_t slot = 0) const override; @@ -53,6 +61,6 @@ class OpenGLESTextureCube : public TextureCube private: std::vector _paths; - std::uint32_t _renderID {}; + std::uint32_t _renderID{}; }; } // namespace moci diff --git a/src/moci/render/opengl/es2/vertex_array.cpp b/src/moci/render/opengl/es2/vertex_array.cpp index 6547de8..8b7d592 100644 --- a/src/moci/render/opengl/es2/vertex_array.cpp +++ b/src/moci/render/opengl/es2/vertex_array.cpp @@ -2,12 +2,10 @@ #include -namespace moci -{ +namespace moci { static auto shaderDataTypeToOpenGlesBaseType(ShaderDataType type) -> GLenum { - switch (type) - { + switch (type) { case moci::ShaderDataType::Float: return GL_FLOAT; case moci::ShaderDataType::Float2: return GL_FLOAT; case moci::ShaderDataType::Float3: return GL_FLOAT; @@ -19,7 +17,9 @@ static auto shaderDataTypeToOpenGlesBaseType(ShaderDataType type) -> GLenum case moci::ShaderDataType::Int3: return GL_INT; case moci::ShaderDataType::Int4: return GL_INT; case moci::ShaderDataType::Bool: return GL_BOOL; - case moci::ShaderDataType::None: MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); return 0; + case moci::ShaderDataType::None: + MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); + return 0; } MOCI_CORE_ASSERT(false, "Unknown ShaderDataType!"); @@ -35,20 +35,28 @@ void OpenGLESVertexArray::bind() const setLayout(); _indexBuffer->bind(); } + void OpenGLESVertexArray::unbind() const { _indexBuffer->unbind(); _vertexBuffer->unbind(); } -void OpenGLESVertexArray::addVertexBuffer(const std::shared_ptr& vertexBuffer) { _vertexBuffer = vertexBuffer; } -void OpenGLESVertexArray::setIndexBuffer(const std::shared_ptr& indexBuffer) { _indexBuffer = indexBuffer; } +void OpenGLESVertexArray::addVertexBuffer(std::shared_ptr const& vertexBuffer) +{ + _vertexBuffer = vertexBuffer; +} + +void OpenGLESVertexArray::setIndexBuffer(std::shared_ptr const& indexBuffer) +{ + _indexBuffer = indexBuffer; +} + void OpenGLESVertexArray::setLayout() const { - const auto& elements = _vertexBuffer->getLayout().getElements(); - for (unsigned int i = 0; i < elements.size(); i++) - { - const auto& element = elements[i]; + auto const& elements = _vertexBuffer->getLayout().getElements(); + for (unsigned int i = 0; i < elements.size(); i++) { + auto const& element = elements[i]; glEnableVertexAttribArray(i); glVertexAttribPointer( // i, // @@ -56,7 +64,7 @@ void OpenGLESVertexArray::setLayout() const shaderDataTypeToOpenGlesBaseType(element.Type), // element.Normalized ? GL_TRUE : GL_FALSE, // _vertexBuffer->getLayout().getStride(), // - (const void*)element.Offset // + (void const*)element.Offset // ); } } diff --git a/src/moci/render/opengl/es2/vertex_array.hpp b/src/moci/render/opengl/es2/vertex_array.hpp index 9ddde74..a8d934d 100644 --- a/src/moci/render/opengl/es2/vertex_array.hpp +++ b/src/moci/render/opengl/es2/vertex_array.hpp @@ -5,8 +5,7 @@ #include -namespace moci -{ +namespace moci { class OpenGLESVertexArray : public VertexArray { @@ -17,11 +16,20 @@ class OpenGLESVertexArray : public VertexArray void bind() const override; void unbind() const override; - void addVertexBuffer(const std::shared_ptr& vertexBuffer) override; - void setIndexBuffer(const std::shared_ptr& indexBuffer) override; + void addVertexBuffer(std::shared_ptr const& vertexBuffer) override; + void setIndexBuffer(std::shared_ptr const& indexBuffer) override; + + [[nodiscard]] auto getVertexBuffer() const + -> std::shared_ptr const& override + { + return _vertexBuffer; + } - [[nodiscard]] auto getVertexBuffer() const -> const std::shared_ptr& override { return _vertexBuffer; } - [[nodiscard]] auto getIndexBuffer() const -> const std::shared_ptr& override { return _indexBuffer; } + [[nodiscard]] auto getIndexBuffer() const + -> std::shared_ptr const& override + { + return _indexBuffer; + } private: void setLayout() const; diff --git a/src/moci/render/opengl/gl4/buffer.cpp b/src/moci/render/opengl/gl4/buffer.cpp index 385fdee..a4a6db8 100644 --- a/src/moci/render/opengl/gl4/buffer.cpp +++ b/src/moci/render/opengl/gl4/buffer.cpp @@ -2,12 +2,11 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include "gl4.hpp" -#include -#include + #include "gl4.hpp" + #include + #include -namespace moci -{ +namespace moci { OpenGLVertexBuffer::OpenGLVertexBuffer(float* vertices, uint32_t size, bool dynamic) { @@ -16,8 +15,11 @@ OpenGLVertexBuffer::OpenGLVertexBuffer(float* vertices, uint32_t size, bool dyna glGenBuffers(1, &_rendererID); glBindBuffer(GL_ARRAY_BUFFER, _rendererID); - if (dynamic) { glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW); } - else { glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW); } + if (dynamic) { + glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW); + } else { + glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW); + } } OpenGLVertexBuffer::~OpenGLVertexBuffer() { glDeleteBuffers(1, &_rendererID); } @@ -26,7 +28,11 @@ void OpenGLVertexBuffer::bind() const { glBindBuffer(GL_ARRAY_BUFFER, _rendererI void OpenGLVertexBuffer::unbind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); } -auto OpenGLVertexBuffer::uploadData(std::uint32_t offset, std::uint32_t size, const void* data) const -> void +auto OpenGLVertexBuffer::uploadData( + std::uint32_t offset, + std::uint32_t size, + void const* data +) const -> void { glBufferSubData(GL_ARRAY_BUFFER, offset, size, data); } @@ -43,8 +49,11 @@ OpenGLIndexBuffer::OpenGLIndexBuffer(IndexBufferSpecs specs) : _specs(specs) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _rendererID); auto const size = _specs.count * sizeof(uint32_t); - if (_specs.isDynamic) { glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW); } - else { glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, _specs.indices.data(), GL_STATIC_DRAW); } + if (_specs.isDynamic) { + glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW); + } else { + glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, _specs.indices.data(), GL_STATIC_DRAW); + } unbind(); } @@ -55,7 +64,8 @@ void OpenGLIndexBuffer::bind() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _re void OpenGLIndexBuffer::unbind() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } -auto OpenGLIndexBuffer::uploadData(std::uint32_t offset, std::span indices) const -> void +auto OpenGLIndexBuffer::uploadData(std::uint32_t offset, std::span indices) + const -> void { auto const size = indices.size() * sizeof(std::uint32_t); auto* data = indices.data(); diff --git a/src/moci/render/opengl/gl4/buffer.hpp b/src/moci/render/opengl/gl4/buffer.hpp index faba936..562d9aa 100644 --- a/src/moci/render/opengl/gl4/buffer.hpp +++ b/src/moci/render/opengl/gl4/buffer.hpp @@ -2,10 +2,9 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include + #include -namespace moci -{ +namespace moci { class OpenGLVertexBuffer : public VertexBuffer { @@ -16,12 +15,15 @@ class OpenGLVertexBuffer : public VertexBuffer void bind() const override; void unbind() const override; - [[nodiscard]] auto getLayout() const -> const BufferLayout& override { return _layout; } - void setLayout(const BufferLayout& layout) override { _layout = layout; } - void uploadData(std::uint32_t offset, std::uint32_t size, const void* data) const override; + [[nodiscard]] auto getLayout() const -> BufferLayout const& override { return _layout; } + + void setLayout(BufferLayout const& layout) override { _layout = layout; } + + void + uploadData(std::uint32_t offset, std::uint32_t size, void const* data) const override; private: - uint32_t _rendererID {}; + uint32_t _rendererID{}; BufferLayout _layout; }; @@ -35,11 +37,12 @@ class OpenGLIndexBuffer : public IndexBuffer void unbind() const override; [[nodiscard]] auto getCount() const -> uint32_t override { return _specs.count; } + void uploadData(std::uint32_t offset, std::span indices) const override; private: IndexBufferSpecs _specs; - std::uint32_t _rendererID {}; + std::uint32_t _rendererID{}; }; } // namespace moci diff --git a/src/moci/render/opengl/gl4/frame_buffer.cpp b/src/moci/render/opengl/gl4/frame_buffer.cpp index 853c9d7..6111429 100644 --- a/src/moci/render/opengl/gl4/frame_buffer.cpp +++ b/src/moci/render/opengl/gl4/frame_buffer.cpp @@ -2,11 +2,10 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include "gl4.hpp" -#include + #include "gl4.hpp" + #include -namespace moci -{ +namespace moci { OpenGLFramebuffer::OpenGLFramebuffer(FramebufferSpecs spec) : specs_(spec) { invalidate(); } @@ -29,28 +28,56 @@ void OpenGLFramebuffer::resize(std::uint32_t width, std::uint32_t height) void OpenGLFramebuffer::invalidate() { - if (renderID_ != 0) { deallocate(); } + if (renderID_ != 0) { + deallocate(); + } glCreateFramebuffers(1, &renderID_); glBindFramebuffer(GL_FRAMEBUFFER, renderID_); glCreateTextures(GL_TEXTURE_2D, 1, &colorAttachment_); glBindTexture(GL_TEXTURE_2D, colorAttachment_); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, specs_.width, specs_.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA8, + specs_.width, + specs_.height, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + nullptr + ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorAttachment_, 0); + glFramebufferTexture2D( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, + colorAttachment_, + 0 + ); glCreateTextures(GL_TEXTURE_2D, 1, &depthAttachment_); glBindTexture(GL_TEXTURE_2D, depthAttachment_); glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH24_STENCIL8, specs_.width, specs_.height); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthAttachment_, 0); - - MOCI_CORE_ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Framebuffer is incomplete!"); + glFramebufferTexture2D( + GL_FRAMEBUFFER, + GL_DEPTH_STENCIL_ATTACHMENT, + GL_TEXTURE_2D, + depthAttachment_, + 0 + ); + + MOCI_CORE_ASSERT( + glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, + "Framebuffer is incomplete!" + ); glBindFramebuffer(GL_FRAMEBUFFER, 0); } + void OpenGLFramebuffer::deallocate() { glDeleteFramebuffers(1, &renderID_); diff --git a/src/moci/render/opengl/gl4/frame_buffer.hpp b/src/moci/render/opengl/gl4/frame_buffer.hpp index 80e913f..2149bc6 100644 --- a/src/moci/render/opengl/gl4/frame_buffer.hpp +++ b/src/moci/render/opengl/gl4/frame_buffer.hpp @@ -5,8 +5,7 @@ #if defined(MOCI_API_OPENGL_MODERN) -namespace moci -{ +namespace moci { class OpenGLFramebuffer : public Framebuffer { @@ -19,8 +18,15 @@ class OpenGLFramebuffer : public Framebuffer void resize(std::uint32_t width, std::uint32_t height) override; - [[nodiscard]] auto getColorAttachmentRendererId() const -> std::uint32_t override { return colorAttachment_; } - [[nodiscard]] auto getSpecification() const -> const FramebufferSpecs& override { return specs_; } + [[nodiscard]] auto getColorAttachmentRendererId() const -> std::uint32_t override + { + return colorAttachment_; + } + + [[nodiscard]] auto getSpecification() const -> FramebufferSpecs const& override + { + return specs_; + } private: void invalidate(); diff --git a/src/moci/render/opengl/gl4/gl4.hpp b/src/moci/render/opengl/gl4/gl4.hpp index 0fe05ea..0c2b2ad 100644 --- a/src/moci/render/opengl/gl4/gl4.hpp +++ b/src/moci/render/opengl/gl4/gl4.hpp @@ -2,12 +2,12 @@ #if MOCI_API_OPENGL_MODERN -#include + #include -#if not defined(MOCI_API_OPENGL_ES) -#include -#endif + #if not defined(MOCI_API_OPENGL_ES) + #include + #endif -#include + #include #endif diff --git a/src/moci/render/opengl/gl4/graphics_context.cpp b/src/moci/render/opengl/gl4/graphics_context.cpp index a917aff..ac5f9df 100644 --- a/src/moci/render/opengl/gl4/graphics_context.cpp +++ b/src/moci/render/opengl/gl4/graphics_context.cpp @@ -2,14 +2,16 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include "gl4.hpp" -#include -#include + #include "gl4.hpp" + #include + #include -namespace moci -{ +namespace moci { -auto GraphicsContext::create(void* win) -> GraphicsContext* { return new OpenGLContext(static_cast(win)); } +auto GraphicsContext::create(void* win) -> GraphicsContext* +{ + return new OpenGLContext(static_cast(win)); +} OpenGLContext::OpenGLContext(GLFWwindow* windowHandle) : _windowHandle(windowHandle) { @@ -22,20 +24,33 @@ void OpenGLContext::init() glfwMakeContextCurrent(_windowHandle); // Initialize OpenGL loader - if (auto err = glewInit() != GLEW_OK; err) { MOCI_CORE_ASSERT(err, "Failed to initialize glew!"); } + if (auto err = glewInit() != GLEW_OK; err) { + MOCI_CORE_ASSERT(err, "Failed to initialize glew!"); + } MOCI_CORE_INFO("OpenGL Info:"); - MOCI_CORE_INFO(" Vendor: {0}", std::string_view {reinterpret_cast(glGetString(GL_VENDOR))}); - MOCI_CORE_INFO(" Renderer: {0}", std::string_view {reinterpret_cast(glGetString(GL_RENDERER))}); - MOCI_CORE_INFO(" Version: {0}", std::string_view {reinterpret_cast(glGetString(GL_VERSION))}); + MOCI_CORE_INFO( + " Vendor: {0}", + std::string_view{reinterpret_cast(glGetString(GL_VENDOR))} + ); + MOCI_CORE_INFO( + " Renderer: {0}", + std::string_view{reinterpret_cast(glGetString(GL_RENDERER))} + ); + MOCI_CORE_INFO( + " Version: {0}", + std::string_view{reinterpret_cast(glGetString(GL_VERSION))} + ); int versionMajor = 0; int versionMinor = 0; glGetIntegerv(GL_MAJOR_VERSION, &versionMajor); glGetIntegerv(GL_MINOR_VERSION, &versionMinor); - MOCI_CORE_ASSERT(versionMajor > 4 || (versionMajor == 4 && versionMinor >= 5), - "Moci requires at least OpenGL version 4.5!"); + MOCI_CORE_ASSERT( + versionMajor > 4 || (versionMajor == 4 && versionMinor >= 5), + "Moci requires at least OpenGL version 4.5!" + ); } void OpenGLContext::swapBuffers() diff --git a/src/moci/render/opengl/gl4/graphics_context.hpp b/src/moci/render/opengl/gl4/graphics_context.hpp index e336ed4..8148190 100644 --- a/src/moci/render/opengl/gl4/graphics_context.hpp +++ b/src/moci/render/opengl/gl4/graphics_context.hpp @@ -2,12 +2,11 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include + #include struct GLFWwindow; -namespace moci -{ +namespace moci { class OpenGLContext : public GraphicsContext { diff --git a/src/moci/render/opengl/gl4/renderer_api.cpp b/src/moci/render/opengl/gl4/renderer_api.cpp index 6161544..d286a1a 100644 --- a/src/moci/render/opengl/gl4/renderer_api.cpp +++ b/src/moci/render/opengl/gl4/renderer_api.cpp @@ -2,55 +2,43 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include "gl4.hpp" + #include "gl4.hpp" -#include + #include -namespace moci -{ +namespace moci { -namespace -{ +namespace { auto MociToOpenGLDrawMode(RenderDrawMode const mode) noexcept -> int { - switch (mode) - { - case RenderDrawMode::None: - { + switch (mode) { + case RenderDrawMode::None: { MOCI_CORE_ERROR("draw mode 'None' not supported"); break; } - case RenderDrawMode::Points: - { + case RenderDrawMode::Points: { return GL_POINTS; } - case RenderDrawMode::LineStrip: - { + case RenderDrawMode::LineStrip: { return GL_LINE_STRIP; } - case RenderDrawMode::LineLoop: - { + case RenderDrawMode::LineLoop: { return GL_LINE_LOOP; } - case RenderDrawMode::Lines: - { + case RenderDrawMode::Lines: { return GL_LINES; } - case RenderDrawMode::TriangleStrips: - { + case RenderDrawMode::TriangleStrips: { return GL_TRIANGLE_STRIP; } - case RenderDrawMode::TriangleFan: - { + case RenderDrawMode::TriangleFan: { return GL_TRIANGLE_FAN; } - case RenderDrawMode::Triangles: - { + case RenderDrawMode::Triangles: { return GL_TRIANGLES; } - default: - { + default: { break; } } @@ -59,8 +47,15 @@ auto MociToOpenGLDrawMode(RenderDrawMode const mode) noexcept -> int } // namespace -void OpenGLMessageCallback(unsigned source, unsigned type, unsigned id, unsigned severity, int length, - const char* message, const void* userParam) +void OpenGLMessageCallback( + unsigned source, + unsigned type, + unsigned id, + unsigned severity, + int length, + char const* message, + void const* userParam +) { ignoreUnused(source); ignoreUnused(type); @@ -68,8 +63,7 @@ void OpenGLMessageCallback(unsigned source, unsigned type, unsigned id, unsigned ignoreUnused(length); ignoreUnused(userParam); - switch (severity) - { + switch (severity) { case GL_DEBUG_SEVERITY_HIGH: MOCI_CORE_CRITICAL(message); return; case GL_DEBUG_SEVERITY_MEDIUM: MOCI_CORE_ERROR(message); return; case GL_DEBUG_SEVERITY_LOW: MOCI_CORE_WARN(message); return; @@ -83,13 +77,20 @@ void OpenGLRendererAPI::init() { MOCI_PROFILE_FUNCTION(); -#ifdef MOCI_DEBUG + #ifdef MOCI_DEBUG glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(OpenGLMessageCallback, nullptr); - glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE); -#endif + glDebugMessageControl( + GL_DONT_CARE, + GL_DONT_CARE, + GL_DEBUG_SEVERITY_NOTIFICATION, + 0, + NULL, + GL_FALSE + ); + #endif glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); @@ -113,22 +114,38 @@ void OpenGLRendererAPI::setClearColor(ColorRGBA32 color) void OpenGLRendererAPI::clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } -void OpenGLRendererAPI::drawArrays(RenderDrawMode const mode, uint32_t first, uint32_t count) +void OpenGLRendererAPI::drawArrays( + RenderDrawMode const mode, + uint32_t first, + uint32_t count +) { auto const glDrawMode = MociToOpenGLDrawMode(mode); glDrawArrays(glDrawMode, first, count); } -void OpenGLRendererAPI::drawIndexed(RenderDrawMode const mode, uint32_t count, void* indices) +void OpenGLRendererAPI::drawIndexed( + RenderDrawMode const mode, + uint32_t count, + void* indices +) { auto const glDrawMode = MociToOpenGLDrawMode(mode); glDrawElements(glDrawMode, count, GL_UNSIGNED_INT, indices); } -void OpenGLRendererAPI::drawIndexed(RenderDrawMode const mode, std::shared_ptr const& vertexArray) +void OpenGLRendererAPI::drawIndexed( + RenderDrawMode const mode, + std::shared_ptr const& vertexArray +) { auto const glDrawMode = MociToOpenGLDrawMode(mode); - glDrawElements(glDrawMode, vertexArray->getIndexBuffer()->getCount(), GL_UNSIGNED_INT, nullptr); + glDrawElements( + glDrawMode, + vertexArray->getIndexBuffer()->getCount(), + GL_UNSIGNED_INT, + nullptr + ); } auto OpenGLRendererAPI::maxTextureSize() -> std::uint32_t @@ -137,12 +154,14 @@ auto OpenGLRendererAPI::maxTextureSize() -> std::uint32_t glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); return static_cast(maxTextureSize); } + auto OpenGLRendererAPI::maxTextureUnits() -> std::uint32_t { GLint maxTextureUnits = 0; glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &maxTextureUnits); return static_cast(maxTextureUnits); } + auto OpenGLRendererAPI::maxVertexAttributes() -> std::uint32_t { GLint maxAttributes = 0; diff --git a/src/moci/render/opengl/gl4/renderer_api.hpp b/src/moci/render/opengl/gl4/renderer_api.hpp index ae5ecd7..1511902 100644 --- a/src/moci/render/opengl/gl4/renderer_api.hpp +++ b/src/moci/render/opengl/gl4/renderer_api.hpp @@ -2,10 +2,9 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include + #include -namespace moci -{ +namespace moci { class OpenGLRendererAPI : public RendererAPI { @@ -18,7 +17,8 @@ class OpenGLRendererAPI : public RendererAPI void drawArrays(RenderDrawMode mode, uint32_t first, uint32_t count) override; void drawIndexed(RenderDrawMode mode, uint32_t count, void* indices) override; - void drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) override; + void drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) + override; auto maxTextureSize() -> std::uint32_t override; auto maxTextureUnits() -> std::uint32_t override; auto maxVertexAttributes() -> std::uint32_t override; diff --git a/src/moci/render/opengl/gl4/shader.cpp b/src/moci/render/opengl/gl4/shader.cpp index bd858ae..9fb7794 100644 --- a/src/moci/render/opengl/gl4/shader.cpp +++ b/src/moci/render/opengl/gl4/shader.cpp @@ -1,31 +1,34 @@ #include "shader.hpp" #if defined(MOCI_API_OPENGL_MODERN) -#include -#include -#include + #include + #include + #include -#include + #include -#include -#include -#include + #include + #include + #include -namespace moci -{ +namespace moci { -namespace -{ +namespace { auto OpenGLShaderTypeFromShaderType(ShaderType type) -> GLenum { - if (type == ShaderType::Vertex) { return GL_VERTEX_SHADER; } - if (type == ShaderType::Fragment) { return GL_FRAGMENT_SHADER; } + if (type == ShaderType::Vertex) { + return GL_VERTEX_SHADER; + } + if (type == ShaderType::Fragment) { + return GL_FRAGMENT_SHADER; + } MOCI_CORE_ASSERT(false, "Unknown shader type!"); return 0; } } // namespace + OpenGLShader::OpenGLShader(std::string const& filepath) { MOCI_PROFILE_FUNCTION(); @@ -38,11 +41,16 @@ OpenGLShader::OpenGLShader(std::string const& filepath) auto lastSlash = filepath.find_last_of("/\\"); lastSlash = lastSlash == std::string::npos ? 0 : lastSlash + 1; auto lastDot = filepath.rfind('.'); - auto count = lastDot == std::string::npos ? filepath.size() - lastSlash : lastDot - lastSlash; - _name = filepath.substr(lastSlash, count); + auto count + = lastDot == std::string::npos ? filepath.size() - lastSlash : lastDot - lastSlash; + _name = filepath.substr(lastSlash, count); } -OpenGLShader::OpenGLShader(std::string name, std::string const& vertexSrc, std::string const& fragmentSrc) +OpenGLShader::OpenGLShader( + std::string name, + std::string const& vertexSrc, + std::string const& fragmentSrc +) : _name(std::move(name)) { MOCI_PROFILE_FUNCTION(); @@ -66,9 +74,8 @@ auto OpenGLShader::ReadFile(std::string const& filepath) -> std::string std::string result; std::ifstream file(filepath, std::ios::in | std::ios::binary); - if (file) - { - auto ss = std::ostringstream {}; + if (file) { + auto ss = std::ostringstream{}; ss << file.rdbuf(); return ss.str(); } @@ -76,14 +83,14 @@ auto OpenGLShader::ReadFile(std::string const& filepath) -> std::string return {}; } -auto OpenGLShader::PreProcess(std::string const& source) -> std::unordered_map +auto OpenGLShader::PreProcess(std::string const& source) + -> std::unordered_map { MOCI_PROFILE_FUNCTION(); - auto shaderSources = std::unordered_map {}; + auto shaderSources = std::unordered_map{}; auto const program = ShaderParser::splitSource(source); - for (auto const& shader : program.shaders) - { + for (auto const& shader : program.shaders) { auto const type = OpenGLShaderTypeFromShaderType(shader.type); shaderSources[type] = shader.source; } @@ -91,30 +98,28 @@ auto OpenGLShader::PreProcess(std::string const& source) -> std::unordered_map& shaderSources) +void OpenGLShader::Compile(std::unordered_map const& shaderSources) { MOCI_PROFILE_FUNCTION(); GLuint program = glCreateProgram(); MOCI_CORE_ASSERT(shaderSources.size() <= 2, "We only support 2 shaders for now"); - std::array glShaderIDs {}; + std::array glShaderIDs{}; int glShaderIDIndex = 0; - for (const auto& kv : shaderSources) - { + for (auto const& kv : shaderSources) { GLenum type = kv.first; std::string const& source = kv.second; GLuint shader = glCreateShader(type); - const GLchar* sourceCStr = source.c_str(); + GLchar const* sourceCStr = source.c_str(); glShaderSource(shader, 1, &sourceCStr, nullptr); glCompileShader(shader); GLint isCompiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled); - if (isCompiled == GL_FALSE) - { + if (isCompiled == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); @@ -140,8 +145,7 @@ void OpenGLShader::Compile(const std::unordered_map& shader // Note the different functions here: glGetProgram* instead of glGetShader*. GLint isLinked = 0; glGetProgramiv(program, GL_LINK_STATUS, (int*)&isLinked); - if (isLinked == GL_FALSE) - { + if (isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); @@ -152,15 +156,16 @@ void OpenGLShader::Compile(const std::unordered_map& shader // We don't need the program anymore. glDeleteProgram(program); - for (auto id : glShaderIDs) { glDeleteShader(id); } + for (auto id : glShaderIDs) { + glDeleteShader(id); + } MOCI_CORE_ERROR("{0}", infoLog.data()); MOCI_CORE_ASSERT(false, "Shader link failure!"); return; } - for (auto id : glShaderIDs) - { + for (auto id : glShaderIDs) { glDetachShader(program, id); glDeleteShader(id); } @@ -178,50 +183,87 @@ void OpenGLShader::unbind() const glUseProgram(0); } -void OpenGLShader::setInt(std::string const& name, int value) { uploadUniformInt(name, value); } -void OpenGLShader::setInts(std::string const& name, int count, int* values) { uploadUniformInts(name, count, values); } -void OpenGLShader::setFloat(std::string const& name, float value) { uploadUniformFloat(name, value); } -void OpenGLShader::setFloat2(std::string const& name, glm::vec2 const& value) { uploadUniformFloat2(name, value); } -void OpenGLShader::setFloat3(std::string const& name, const glm::vec3& value) { uploadUniformFloat3(name, value); } -void OpenGLShader::setFloat4(std::string const& name, const glm::vec4& value) { uploadUniformFloat4(name, value); } -void OpenGLShader::setMat3(std::string const& name, glm::mat3 const& value) { uploadUniformMat3(name, value); } -void OpenGLShader::setMat4(std::string const& name, const glm::mat4& value) { uploadUniformMat4(name, value); } +void OpenGLShader::setInt(std::string const& name, int value) +{ + uploadUniformInt(name, value); +} + +void OpenGLShader::setInts(std::string const& name, int count, int* values) +{ + uploadUniformInts(name, count, values); +} + +void OpenGLShader::setFloat(std::string const& name, float value) +{ + uploadUniformFloat(name, value); +} + +void OpenGLShader::setFloat2(std::string const& name, glm::vec2 const& value) +{ + uploadUniformFloat2(name, value); +} + +void OpenGLShader::setFloat3(std::string const& name, glm::vec3 const& value) +{ + uploadUniformFloat3(name, value); +} + +void OpenGLShader::setFloat4(std::string const& name, glm::vec4 const& value) +{ + uploadUniformFloat4(name, value); +} + +void OpenGLShader::setMat3(std::string const& name, glm::mat3 const& value) +{ + uploadUniformMat3(name, value); +} + +void OpenGLShader::setMat4(std::string const& name, glm::mat4 const& value) +{ + uploadUniformMat4(name, value); +} auto OpenGLShader::getLocation(std::string const& name) const -> std::int32_t { return glGetUniformLocation(_rendererID, name.c_str()); } -void OpenGLShader::uploadUniformInt(std::string const& name, int value) { glUniform1i(getLocation(name), value); } +void OpenGLShader::uploadUniformInt(std::string const& name, int value) +{ + glUniform1i(getLocation(name), value); +} void OpenGLShader::uploadUniformInts(std::string const& name, int count, int* values) { glUniform1iv(getLocation(name), count, values); } -void OpenGLShader::uploadUniformFloat(std::string const& name, float value) { glUniform1f(getLocation(name), value); } +void OpenGLShader::uploadUniformFloat(std::string const& name, float value) +{ + glUniform1f(getLocation(name), value); +} -void OpenGLShader::uploadUniformFloat2(std::string const& name, const glm::vec2& value) +void OpenGLShader::uploadUniformFloat2(std::string const& name, glm::vec2 const& value) { glUniform2f(getLocation(name), value.x, value.y); } -void OpenGLShader::uploadUniformFloat3(std::string const& name, const glm::vec3& value) +void OpenGLShader::uploadUniformFloat3(std::string const& name, glm::vec3 const& value) { glUniform3f(getLocation(name), value.x, value.y, value.z); } -void OpenGLShader::uploadUniformFloat4(std::string const& name, const glm::vec4& value) +void OpenGLShader::uploadUniformFloat4(std::string const& name, glm::vec4 const& value) { glUniform4f(getLocation(name), value.x, value.y, value.z, value.w); } -void OpenGLShader::uploadUniformMat3(std::string const& name, const glm::mat3& matrix) +void OpenGLShader::uploadUniformMat3(std::string const& name, glm::mat3 const& matrix) { glUniformMatrix3fv(getLocation(name), 1, GL_FALSE, glm::value_ptr(matrix)); } -void OpenGLShader::uploadUniformMat4(std::string const& name, const glm::mat4& matrix) +void OpenGLShader::uploadUniformMat4(std::string const& name, glm::mat4 const& matrix) { glUniformMatrix4fv(getLocation(name), 1, GL_FALSE, glm::value_ptr(matrix)); } diff --git a/src/moci/render/opengl/gl4/shader.hpp b/src/moci/render/opengl/gl4/shader.hpp index d514360..b9c6eb6 100644 --- a/src/moci/render/opengl/gl4/shader.hpp +++ b/src/moci/render/opengl/gl4/shader.hpp @@ -2,24 +2,27 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include + #include -#include + #include -#include -#include + #include + #include // TODO: REMOVE! using GLenum = unsigned int; -namespace moci -{ +namespace moci { class OpenGLShader : public Shader { public: explicit OpenGLShader(std::string const& filepath); - OpenGLShader(std::string name, std::string const& vertexSrc, std::string const& fragmentSrc); + OpenGLShader( + std::string name, + std::string const& vertexSrc, + std::string const& fragmentSrc + ); ~OpenGLShader() override; [[nodiscard]] auto getName() const -> std::string const& override { return _name; } @@ -42,17 +45,18 @@ class OpenGLShader : public Shader void uploadUniformInt(std::string const& name, int value); void uploadUniformInts(std::string const& name, int count, int* values); void uploadUniformFloat(std::string const& name, float value); - void uploadUniformFloat2(std::string const& name, const glm::vec2& value); - void uploadUniformFloat3(std::string const& name, const glm::vec3& value); - void uploadUniformFloat4(std::string const& name, const glm::vec4& value); - void uploadUniformMat3(std::string const& name, const glm::mat3& matrix); - void uploadUniformMat4(std::string const& name, const glm::mat4& matrix); + void uploadUniformFloat2(std::string const& name, glm::vec2 const& value); + void uploadUniformFloat3(std::string const& name, glm::vec3 const& value); + void uploadUniformFloat4(std::string const& name, glm::vec4 const& value); + void uploadUniformMat3(std::string const& name, glm::mat3 const& matrix); + void uploadUniformMat4(std::string const& name, glm::mat4 const& matrix); static auto ReadFile(std::string const& filepath) -> std::string; - static auto PreProcess(std::string const& source) -> std::unordered_map; - void Compile(const std::unordered_map& shaderSources); + static auto PreProcess(std::string const& source) + -> std::unordered_map; + void Compile(std::unordered_map const& shaderSources); - uint32_t _rendererID {}; + uint32_t _rendererID{}; std::string _name; }; diff --git a/src/moci/render/opengl/gl4/texture.cpp b/src/moci/render/opengl/gl4/texture.cpp index f922cba..faa25af 100644 --- a/src/moci/render/opengl/gl4/texture.cpp +++ b/src/moci/render/opengl/gl4/texture.cpp @@ -2,17 +2,20 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include "gl4.hpp" + #include "gl4.hpp" -#include + #include -#include + #include -namespace moci -{ +namespace moci { OpenGLTexture2D::OpenGLTexture2D(std::uint32_t width, std::uint32_t height) - : width_ {width}, height_ {height}, channels_ {4}, internalFormat_ {GL_RGBA8}, dataFormat_ {GL_RGBA} + : width_{width} + , height_{height} + , channels_{4} + , internalFormat_{GL_RGBA8} + , dataFormat_{GL_RGBA} { createTexture(); setFilters(); @@ -50,29 +53,51 @@ OpenGLTexture2D::OpenGLTexture2D(std::string path) : path_(std::move(path)) createTexture(); setFilters(); - setData( - std::span {reinterpret_cast(data), static_cast(width_ * height_ * channels_)}); + setData(std::span{ + reinterpret_cast(data), + static_cast(width_ * height_ * channels_) + }); stbi_image_free(data); } -OpenGLTexture2D::OpenGLTexture2D(Texture::Format format, std::uint32_t width, std::uint32_t height, void* data) - : width_(width), height_(height) +OpenGLTexture2D::OpenGLTexture2D( + Texture::Format format, + std::uint32_t width, + std::uint32_t height, + void* data +) + : width_(width) + , height_(height) { ignoreUnused(format); createTexture(); setFilters(); - setData( - std::span {reinterpret_cast(data), static_cast(width_ * height_ * channels_)}); + setData(std::span{ + reinterpret_cast(data), + static_cast(width_ * height_ * channels_) + }); } OpenGLTexture2D::~OpenGLTexture2D() { glDeleteTextures(1, &renderID_); } void OpenGLTexture2D::setData(std::span data) const { - MOCI_CORE_ASSERT(data.size() == static_cast(width_ * height_ * channels_), - "Data must be entire texture!"); - glTextureSubImage2D(renderID_, 0, 0, 0, width_, height_, dataFormat_, GL_UNSIGNED_BYTE, data.data()); + MOCI_CORE_ASSERT( + data.size() == static_cast(width_ * height_ * channels_), + "Data must be entire texture!" + ); + glTextureSubImage2D( + renderID_, + 0, + 0, + 0, + width_, + height_, + dataFormat_, + GL_UNSIGNED_BYTE, + data.data() + ); } void OpenGLTexture2D::bind(uint32_t slot) const { glBindTextureUnit(slot, renderID_); } @@ -92,7 +117,8 @@ void OpenGLTexture2D::setFilters() const glTextureParameteri(renderID_, GL_TEXTURE_WRAP_T, GL_REPEAT); } -OpenGLTextureCube::OpenGLTextureCube(std::vector paths) : paths_(std::move(paths)) +OpenGLTextureCube::OpenGLTextureCube(std::vector paths) + : paths_(std::move(paths)) { // Generate a texture object @@ -109,19 +135,28 @@ OpenGLTextureCube::OpenGLTextureCube(std::vector paths) : paths_(st glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // stbi_set_flip_vertically_on_load(1); - for (GLuint i = 0; i < paths_.size(); i++) - { + for (GLuint i = 0; i < paths_.size(); i++) { int width = 0; int height = 0; int nrChannels = 0; auto* data = stbi_load(paths_[i].c_str(), &width, &height, &nrChannels, 0); - if (data != nullptr) - { + if (data != nullptr) { MOCI_CORE_INFO("stbi loaded: {} {}x{}", paths_[i].c_str(), width, height); auto const position = GL_TEXTURE_CUBE_MAP_POSITIVE_X + i; - glTexImage2D(position, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); + glTexImage2D( + position, + 0, + GL_RGB, + width, + height, + 0, + GL_RGB, + GL_UNSIGNED_BYTE, + data + ); + } else { + MOCI_CORE_ERROR("stbi error: {}", paths_[i].c_str()); } - else { MOCI_CORE_ERROR("stbi error: {}", paths_[i].c_str()); } stbi_image_free(data); } diff --git a/src/moci/render/opengl/gl4/texture.hpp b/src/moci/render/opengl/gl4/texture.hpp index e0887e5..af1dfa6 100644 --- a/src/moci/render/opengl/gl4/texture.hpp +++ b/src/moci/render/opengl/gl4/texture.hpp @@ -2,31 +2,39 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include "gl4.hpp" + #include "gl4.hpp" -#include + #include -#include -namespace moci -{ + #include + +namespace moci { class OpenGLTexture2D : public Texture2D { public: OpenGLTexture2D(std::uint32_t width, std::uint32_t height); explicit OpenGLTexture2D(std::string path); - OpenGLTexture2D(Texture::Format format, std::uint32_t width, std::uint32_t height, void* data); + OpenGLTexture2D( + Texture::Format format, + std::uint32_t width, + std::uint32_t height, + void* data + ); ~OpenGLTexture2D() override; [[nodiscard]] auto getWidth() const -> std::uint32_t override { return width_; } + [[nodiscard]] auto getHeight() const -> std::uint32_t override { return height_; } + [[nodiscard]] auto getId() const -> std::uint32_t override { return renderID_; } void setData(std::span data) const; void bind(std::uint32_t slot = 0) const override; - void unbind() const override { } + + void unbind() const override {} private: void createTexture(); @@ -35,10 +43,10 @@ class OpenGLTexture2D : public Texture2D std::string path_; std::uint32_t width_; std::uint32_t height_; - std::uint32_t channels_ {}; - std::uint32_t renderID_ {}; - GLenum internalFormat_ {}; - GLenum dataFormat_ {}; + std::uint32_t channels_{}; + std::uint32_t renderID_{}; + GLenum internalFormat_{}; + GLenum dataFormat_{}; }; class OpenGLTextureCube : public TextureCube @@ -46,13 +54,15 @@ class OpenGLTextureCube : public TextureCube public: explicit OpenGLTextureCube(std::vector paths); - OpenGLTextureCube(const OpenGLTextureCube&) = delete; - auto operator=(const OpenGLTextureCube&) -> OpenGLTextureCube& = delete; + OpenGLTextureCube(OpenGLTextureCube const&) = delete; + auto operator=(OpenGLTextureCube const&) -> OpenGLTextureCube& = delete; ~OpenGLTextureCube() override; [[nodiscard]] auto getWidth() const -> std::uint32_t override { return 0; } + [[nodiscard]] auto getHeight() const -> std::uint32_t override { return 0; } + [[nodiscard]] auto getId() const -> std::uint32_t override { return renderID_; } void bind(std::uint32_t slot = 0) const override; @@ -60,7 +70,7 @@ class OpenGLTextureCube : public TextureCube private: std::vector paths_; - std::uint32_t renderID_ {}; + std::uint32_t renderID_{}; }; } // namespace moci diff --git a/src/moci/render/opengl/gl4/vertex_array.cpp b/src/moci/render/opengl/gl4/vertex_array.cpp index 16ee896..864f0b6 100644 --- a/src/moci/render/opengl/gl4/vertex_array.cpp +++ b/src/moci/render/opengl/gl4/vertex_array.cpp @@ -2,16 +2,14 @@ #if defined(MOCI_API_OPENGL_MODERN) -#include "gl4.hpp" -#include + #include "gl4.hpp" + #include -namespace moci -{ +namespace moci { static auto ShaderDataTypeToOpenGLBaseType(ShaderDataType type) -> GLenum { - switch (type) - { + switch (type) { case ShaderDataType::Float: return GL_FLOAT; case ShaderDataType::Float2: return GL_FLOAT; case ShaderDataType::Float3: return GL_FLOAT; @@ -43,21 +41,28 @@ void OpenGLVertexArray::bind() const { glBindVertexArray(_rendererID); } void OpenGLVertexArray::unbind() const { glBindVertexArray(0); } -void OpenGLVertexArray::addVertexBuffer(const std::shared_ptr& vertexBuffer) +void OpenGLVertexArray::addVertexBuffer(std::shared_ptr const& vertexBuffer) { - MOCI_CORE_ASSERT(vertexBuffer->getLayout().getElements().size(), "Vertex Buffer has no layout!"); + MOCI_CORE_ASSERT( + vertexBuffer->getLayout().getElements().size(), + "Vertex Buffer has no layout!" + ); glBindVertexArray(_rendererID); vertexBuffer->bind(); - const auto& layout = vertexBuffer->getLayout(); - for (const auto& element : layout) - { + auto const& layout = vertexBuffer->getLayout(); + for (auto const& element : layout) { glEnableVertexAttribArray(_vertexBufferIndex); - glVertexAttribPointer(_vertexBufferIndex, element.getComponentCount(), - ShaderDataTypeToOpenGLBaseType(element.Type), element.Normalized ? GL_TRUE : GL_FALSE, - layout.getStride(), (const void*)element.Offset); + glVertexAttribPointer( + _vertexBufferIndex, + element.getComponentCount(), + ShaderDataTypeToOpenGLBaseType(element.Type), + element.Normalized ? GL_TRUE : GL_FALSE, + layout.getStride(), + (void const*)element.Offset + ); _vertexBufferIndex++; } @@ -65,7 +70,7 @@ void OpenGLVertexArray::addVertexBuffer(const std::shared_ptr& ver // _vertexBuffers.push_back(vertexBuffer); } -void OpenGLVertexArray::setIndexBuffer(const std::shared_ptr& indexBuffer) +void OpenGLVertexArray::setIndexBuffer(std::shared_ptr const& indexBuffer) { glBindVertexArray(_rendererID); diff --git a/src/moci/render/opengl/gl4/vertex_array.hpp b/src/moci/render/opengl/gl4/vertex_array.hpp index 51bf996..fabfc0d 100644 --- a/src/moci/render/opengl/gl4/vertex_array.hpp +++ b/src/moci/render/opengl/gl4/vertex_array.hpp @@ -4,8 +4,7 @@ #include #if defined(MOCI_API_OPENGL_MODERN) -namespace moci -{ +namespace moci { class OpenGLVertexArray : public VertexArray { @@ -16,14 +15,23 @@ class OpenGLVertexArray : public VertexArray void bind() const override; void unbind() const override; - void addVertexBuffer(const std::shared_ptr& vertexBuffer) override; - void setIndexBuffer(const std::shared_ptr& indexBuffer) override; + void addVertexBuffer(std::shared_ptr const& vertexBuffer) override; + void setIndexBuffer(std::shared_ptr const& indexBuffer) override; + + [[nodiscard]] auto getVertexBuffer() const + -> std::shared_ptr const& override + { + return _vertexBuffer; + } - [[nodiscard]] auto getVertexBuffer() const -> const std::shared_ptr& override { return _vertexBuffer; } - [[nodiscard]] auto getIndexBuffer() const -> const std::shared_ptr& override { return _indexBuffer; } + [[nodiscard]] auto getIndexBuffer() const + -> std::shared_ptr const& override + { + return _indexBuffer; + } private: - uint32_t _rendererID {}; + uint32_t _rendererID{}; uint32_t _vertexBufferIndex = 0; std::shared_ptr _vertexBuffer; std::shared_ptr _indexBuffer; diff --git a/src/moci/render/render_command.cpp b/src/moci/render/render_command.cpp index fbecf02..2adb5ec 100644 --- a/src/moci/render/render_command.cpp +++ b/src/moci/render/render_command.cpp @@ -3,11 +3,12 @@ #include #include -namespace moci -{ +namespace moci { #if defined(MOCI_API_OPENGL_LEGACY) -std::unique_ptr RenderCommand::sRendererApi = std::make_unique(); +std::unique_ptr RenderCommand::sRendererApi + = std::make_unique(); #else -std::unique_ptr RenderCommand::sRendererApi = std::make_unique(); +std::unique_ptr RenderCommand::sRendererApi + = std::make_unique(); #endif } // namespace moci diff --git a/src/moci/render/render_command.hpp b/src/moci/render/render_command.hpp index 4aa9db3..13e87ac 100644 --- a/src/moci/render/render_command.hpp +++ b/src/moci/render/render_command.hpp @@ -5,8 +5,7 @@ #include #include -namespace moci -{ +namespace moci { class RenderCommand { @@ -47,16 +46,32 @@ class RenderCommand sRendererApi->drawIndexed(mode, count, indices); } - inline static void drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) + inline static void + drawIndexed(RenderDrawMode mode, std::shared_ptr const& vertexArray) { MOCI_PROFILE_FUNCTION(); sRendererApi->drawIndexed(mode, vertexArray); } - inline static auto maxTextureSize() -> std::uint32_t { return sRendererApi->maxTextureSize(); } - inline static auto maxTextureUnits() -> std::uint32_t { return sRendererApi->maxTextureUnits(); } - inline static auto maxVertexAttributes() -> std::uint32_t { return sRendererApi->maxVertexAttributes(); } - inline static auto maxUniformVectors() -> std::uint32_t { return sRendererApi->maxUniformVectors(); } + inline static auto maxTextureSize() -> std::uint32_t + { + return sRendererApi->maxTextureSize(); + } + + inline static auto maxTextureUnits() -> std::uint32_t + { + return sRendererApi->maxTextureUnits(); + } + + inline static auto maxVertexAttributes() -> std::uint32_t + { + return sRendererApi->maxVertexAttributes(); + } + + inline static auto maxUniformVectors() -> std::uint32_t + { + return sRendererApi->maxUniformVectors(); + } private: static std::unique_ptr sRendererApi; diff --git a/src/moci/render/render_factory.cpp b/src/moci/render/render_factory.cpp index 32b5a9d..42a6d0e 100644 --- a/src/moci/render/render_factory.cpp +++ b/src/moci/render/render_factory.cpp @@ -14,28 +14,24 @@ #include #include -namespace moci -{ +namespace moci { -auto RenderFactory::makeVertexBuffer(float* vertices, uint32_t size, bool dynamic) -> VertexBuffer* +auto RenderFactory::makeVertexBuffer(float* vertices, uint32_t size, bool dynamic) + -> VertexBuffer* { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL Vertex Buffer"); return new OpenGLVertexBuffer(vertices, size, dynamic); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES Vertex Buffer"); return new OpenGLESVertexBuffer(vertices, size, dynamic); } @@ -49,23 +45,19 @@ auto RenderFactory::makeVertexBuffer(float* vertices, uint32_t size, bool dynami auto RenderFactory::makeIndexBuffer(IndexBufferSpecs specs) -> IndexBuffer* { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL Index Buffer"); return new OpenGLIndexBuffer(specs); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES Index Buffer"); return new OpenGLESIndexBuffer(specs); } @@ -79,23 +71,19 @@ auto RenderFactory::makeIndexBuffer(IndexBufferSpecs specs) -> IndexBuffer* auto RenderFactory::makeFramebuffer(FramebufferSpecs spec) -> std::shared_ptr { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL FrameBuffer"); return std::make_shared(spec); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES FrameBuffer"); return std::make_shared(spec); } @@ -107,26 +95,22 @@ auto RenderFactory::makeFramebuffer(FramebufferSpecs spec) -> std::shared_ptr std::shared_ptr +auto RenderFactory::makeShader(std::string const& filepath) -> std::shared_ptr { MOCI_CORE_INFO("Creating shader from: {}", filepath); - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL Shader: {:s}", filepath); return std::make_shared(filepath); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES Shader: {:s}", filepath); return std::make_shared(filepath); } @@ -138,26 +122,25 @@ auto RenderFactory::makeShader(const std::string& filepath) -> std::shared_ptr std::shared_ptr +auto RenderFactory::makeShader( + std::string const& name, + std::string const& vertexSrc, + std::string const& fragmentSrc +) -> std::shared_ptr { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL Shader: {:s}", name); return std::make_shared(name, vertexSrc, fragmentSrc); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES Shader: {:s}", name); return std::make_shared(name, vertexSrc, fragmentSrc); } @@ -171,23 +154,19 @@ auto RenderFactory::makeShader(std::string const& name, std::string const& verte auto RenderFactory::makeTexture2D(std::string const& path) -> std::shared_ptr { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL Texture2D: {:s}", path); return std::make_shared(path); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES Texture2D: {:s}", path); return std::make_shared(path); } @@ -199,25 +178,26 @@ auto RenderFactory::makeTexture2D(std::string const& path) -> std::shared_ptr std::shared_ptr +auto RenderFactory::makeTexture2D( + Texture::Format format, + uint32_t width, + uint32_t height, + void* data +) -> std::shared_ptr { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL Texture2D from data"); return std::make_shared(format, width, height, data); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES Texture2D from data"); return std::make_shared(format, width, height, data); } @@ -229,25 +209,22 @@ auto RenderFactory::makeTexture2D(Texture::Format format, uint32_t width, uint32 return nullptr; } -auto RenderFactory::makeTextureCube(const std::vector& paths) -> std::shared_ptr +auto RenderFactory::makeTextureCube(std::vector const& paths) + -> std::shared_ptr { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL TextureCube"); return std::make_shared(paths); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES TextureCube"); return std::make_shared(paths); } @@ -261,23 +238,19 @@ auto RenderFactory::makeTextureCube(const std::vector& paths) -> st auto RenderFactory::makeVertexArray() -> std::shared_ptr { - switch (Renderer::getApi()) - { - case RendererAPI::API::None: - { + switch (Renderer::getApi()) { + case RendererAPI::API::None: { MOCI_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; } #if defined(MOCI_API_OPENGL_MODERN) - case RendererAPI::API::OpenGL: - { + case RendererAPI::API::OpenGL: { MOCI_CORE_INFO("Make OpenGL VertexArray"); return std::make_shared(); } #endif #if defined(MOCI_API_OPENGL_LEGACY) - case RendererAPI::API::OpenGLES: - { + case RendererAPI::API::OpenGLES: { MOCI_CORE_INFO("Make OpenGLES VertexArray"); return std::make_shared(); } diff --git a/src/moci/render/render_factory.hpp b/src/moci/render/render_factory.hpp index c0f9876..7599a97 100644 --- a/src/moci/render/render_factory.hpp +++ b/src/moci/render/render_factory.hpp @@ -6,19 +6,25 @@ #include #include -namespace moci -{ +namespace moci { struct RenderFactory { - static auto makeVertexBuffer(float* vertices, std::uint32_t size, bool dynamic = false) -> VertexBuffer*; + static auto makeVertexBuffer(float* vertices, std::uint32_t size, bool dynamic = false) + -> VertexBuffer*; static auto makeIndexBuffer(IndexBufferSpecs specs) -> IndexBuffer*; static auto makeFramebuffer(FramebufferSpecs spec) -> std::shared_ptr; - static auto makeShader(const std::string& filepath) -> std::shared_ptr; - static auto makeShader(std::string const& name, std::string const& vertexSrc, std::string const& fragmentSrc) - -> std::shared_ptr; + static auto makeShader(std::string const& filepath) -> std::shared_ptr; + static auto makeShader( + std::string const& name, + std::string const& vertexSrc, + std::string const& fragmentSrc + ) -> std::shared_ptr; static auto makeTexture2D(std::string const& path) -> std::shared_ptr; - static auto makeTexture2D(Texture::Format format, uint32_t width, uint32_t height, void* data) -> std::shared_ptr; - static auto makeTextureCube(const std::vector& paths) -> std::shared_ptr; + static auto + makeTexture2D(Texture::Format format, uint32_t width, uint32_t height, void* data) + -> std::shared_ptr; + static auto makeTextureCube(std::vector const& paths) + -> std::shared_ptr; static auto makeVertexArray() -> std::shared_ptr; }; diff --git a/src/moci/render/renderer.cpp b/src/moci/render/renderer.cpp index 968de0b..3233251 100644 --- a/src/moci/render/renderer.cpp +++ b/src/moci/render/renderer.cpp @@ -4,10 +4,10 @@ // #include "Platform/OpenGLES/OpenGLESShader.h" // #include "Renderer2D.h" -namespace moci -{ +namespace moci { -// std::unique_ptr Renderer::s_SceneData = CreateScope(); +// std::unique_ptr Renderer::s_SceneData = +// CreateScope(); void Renderer::init() { @@ -17,7 +17,7 @@ void Renderer::init() void Renderer::onWindowResize(uint32_t width, uint32_t height) { - RenderCommand::setViewport(Rectangle {0, 0, width, height}); + RenderCommand::setViewport(Rectangle{0, 0, width, height}); } // void Renderer::BeginScene(OrthographicCamera& camera) @@ -27,20 +27,24 @@ void Renderer::onWindowResize(uint32_t width, uint32_t height) // void Renderer::EndScene() {} -// void Renderer::Submit(const std::shared_ptr& shader, const std::shared_ptr& vertexArray, +// void Renderer::Submit(const std::shared_ptr& shader, const +// std::shared_ptr& vertexArray, // const glm::mat4& transform) // { // shader->Bind(); -// // std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_ViewProjection", +// // +// std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_ViewProjection", // // s_SceneData->ViewProjectionMatrix); -// // std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_Transform", transform); +// // std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_Transform", +// transform); -// std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_ViewProjection", -// s_SceneData->ViewProjectionMatrix); -// std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_Transform", transform); +// std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_ViewProjection", +// s_SceneData->ViewProjectionMatrix); +// std::dynamic_pointer_cast(shader)->UploadUniformMat4("u_Transform", +// transform); -// vertexArray->Bind(); -// RenderCommand::DrawIndexed(vertexArray); +// vertexArray->Bind(); +// RenderCommand::DrawIndexed(vertexArray); // } } // namespace moci diff --git a/src/moci/render/renderer.hpp b/src/moci/render/renderer.hpp index f0436d4..5c1c998 100644 --- a/src/moci/render/renderer.hpp +++ b/src/moci/render/renderer.hpp @@ -4,8 +4,7 @@ #include -namespace moci -{ +namespace moci { class Renderer { @@ -16,7 +15,8 @@ class Renderer // static void BeginScene(OrthographicCamera& camera); // static void EndScene(); - // static void Submit(const std::shared_ptr& shader, const std::shared_ptr& vertexArray, + // static void Submit(const std::shared_ptr& shader, const + // std::shared_ptr& vertexArray, // const glm::mat4& transform = glm::mat4(1.0f)); inline static auto getApi() -> RendererAPI::API { return RendererAPI::getApi(); } diff --git a/src/moci/render/renderer_api.cpp b/src/moci/render/renderer_api.cpp index d148cdd..bda64cd 100644 --- a/src/moci/render/renderer_api.cpp +++ b/src/moci/render/renderer_api.cpp @@ -1,13 +1,12 @@ #include -namespace moci -{ +namespace moci { #if defined(MOCI_API_OPENGL_LEGACY) RendererAPI::API RendererAPI::sApi = RendererAPI::API::OpenGLES; #elif defined(MOCI_API_OPENGL_MODERN) RendererAPI::API RendererAPI::sApi = RendererAPI::API::OpenGL; #else -#error "Unsupported API" + #error "Unsupported API" #endif } // namespace moci diff --git a/src/moci/render/shader.hpp b/src/moci/render/shader.hpp index e41727a..c3b4ae6 100644 --- a/src/moci/render/shader.hpp +++ b/src/moci/render/shader.hpp @@ -6,8 +6,7 @@ #include #include -namespace moci -{ +namespace moci { enum class ShaderType { Unknown = 0, diff --git a/src/moci/render/texture.hpp b/src/moci/render/texture.hpp index 6782ebf..4009f99 100644 --- a/src/moci/render/texture.hpp +++ b/src/moci/render/texture.hpp @@ -7,8 +7,7 @@ #include #include -namespace moci -{ +namespace moci { class Texture { diff --git a/src/moci/render/vertex_array.hpp b/src/moci/render/vertex_array.hpp index 070ab79..2768334 100644 --- a/src/moci/render/vertex_array.hpp +++ b/src/moci/render/vertex_array.hpp @@ -4,8 +4,7 @@ #include -namespace moci -{ +namespace moci { class VertexArray { @@ -15,11 +14,13 @@ class VertexArray virtual void bind() const = 0; virtual void unbind() const = 0; - virtual void addVertexBuffer(const std::shared_ptr& vertexBuffer) = 0; - virtual void setIndexBuffer(const std::shared_ptr& indexBuffer) = 0; + virtual void addVertexBuffer(std::shared_ptr const& vertexBuffer) = 0; + virtual void setIndexBuffer(std::shared_ptr const& indexBuffer) = 0; - [[nodiscard]] virtual auto getVertexBuffer() const -> const std::shared_ptr& = 0; - [[nodiscard]] virtual auto getIndexBuffer() const -> const std::shared_ptr& = 0; + [[nodiscard]] virtual auto getVertexBuffer() const + -> std::shared_ptr const& = 0; + [[nodiscard]] virtual auto getIndexBuffer() const + -> std::shared_ptr const& = 0; }; } // namespace moci diff --git a/src/moci/widgets/component/button.cpp b/src/moci/widgets/component/button.cpp index 702db9e..20432f1 100644 --- a/src/moci/widgets/component/button.cpp +++ b/src/moci/widgets/component/button.cpp @@ -4,36 +4,47 @@ #include -namespace moci -{ -Button::Button(std::string text, ButtonSpecs specs) : Component(text), _text(std::move(text)), _specs(std::move(specs)) -{ -} +namespace moci { +Button::Button(std::string text, ButtonSpecs specs) + : Component(text) + , _text(std::move(text)) + , _specs(std::move(specs)) +{} void Button::onDraw(Painter& painter) { auto* style = getStyle(); - MOCI_CORE_ASSERT(style != nullptr, "If yo hit this assertion, you probably forgot" - "to set the style on the top level component."); + MOCI_CORE_ASSERT( + style != nullptr, + "If yo hit this assertion, you probably forgot" + "to set the style on the top level component." + ); style->drawButton(painter, getBounds(), *this); } auto Button::setSpecs(ButtonSpecs newSpecs) -> void { _specs = std::move(newSpecs); } + auto Button::getSpecs() const noexcept -> ButtonSpecs { return _specs; } auto Button::setState(ButtonState newState) -> void { _state = newState; - if (_specs.callbacks.stateChanged) { _specs.callbacks.stateChanged(newState); } + if (_specs.callbacks.stateChanged) { + _specs.callbacks.stateChanged(newState); + } } + auto Button::getState() const noexcept -> ButtonState { return _state; } auto Button::setText(std::string newText) -> void { _text = std::move(newText); } + auto Button::getText() const noexcept -> std::string const& { return _text; } + auto Button::getTextView() const noexcept -> std::string_view { return _text; } void Button::setTextColor(ColorRGBA32 col) noexcept { _color = col; } + auto Button::getTextColor() const noexcept -> ColorRGBA32 { return _color; } auto Button::mouseClicked(moci::MouseCallback::Click click) -> bool diff --git a/src/moci/widgets/component/button.hpp b/src/moci/widgets/component/button.hpp index a7230ac..a11aa75 100644 --- a/src/moci/widgets/component/button.hpp +++ b/src/moci/widgets/component/button.hpp @@ -5,8 +5,7 @@ #include #include -namespace moci -{ +namespace moci { class Button; enum class ButtonState @@ -21,7 +20,8 @@ class ButtonStyleMethods public: virtual ~ButtonStyleMethods() = default; - virtual void drawButton(Painter& painter, Rectangle bounds, Button const& button) = 0; + virtual void drawButton(Painter& painter, Rectangle bounds, Button const& button) + = 0; }; struct ButtonCallbacks @@ -39,7 +39,7 @@ struct ButtonSpecs class Button : public Component { public: - explicit Button(std::string text, ButtonSpecs specs = ButtonSpecs {}); + explicit Button(std::string text, ButtonSpecs specs = ButtonSpecs{}); ~Button() override = default; auto onDraw(Painter& painter) -> void override; diff --git a/src/moci/widgets/component/button.test.cpp b/src/moci/widgets/component/button.test.cpp index d4adf30..1ddb266 100644 --- a/src/moci/widgets/component/button.test.cpp +++ b/src/moci/widgets/component/button.test.cpp @@ -9,14 +9,14 @@ TEST_CASE("widget: ButtonConstruct", "[ui]") { - moci::Button const button {"test"}; + moci::Button const button{"test"}; REQUIRE(button.getText() == "test"); REQUIRE(button.getTextView() == "test"); } TEST_CASE("widget: ButtonSetText", "[ui]") { - moci::Button button {""}; + moci::Button button{""}; REQUIRE(button.getText().empty()); REQUIRE(button.getTextView() == ""); button.SetText("test143"); @@ -26,7 +26,7 @@ TEST_CASE("widget: ButtonSetText", "[ui]") TEST_CASE("widget: ButtonSetTextColor", "[ui]") { - moci::Button button {""}; + moci::Button button{""}; auto c1 = button.getTextColor(); REQUIRE(c1.red() == 0.0f); @@ -45,7 +45,7 @@ TEST_CASE("widget: ButtonSetTextColor", "[ui]") TEST_CASE("widget: ButtonSetSpecs", "[ui]") { - moci::Button button {""}; + moci::Button button{""}; { auto specs = button.getSpecs(); @@ -53,7 +53,7 @@ TEST_CASE("widget: ButtonSetSpecs", "[ui]") REQUIRE(specs.isToggle == false); } - auto newSpecs = moci::ButtonSpecs {}; + auto newSpecs = moci::ButtonSpecs{}; newSpecs.callbacks.clicked = [](auto state) { moci::IgnoreUnused(state); }; newSpecs.isToggle = true; button.SetSpecs(newSpecs); @@ -67,7 +67,7 @@ TEST_CASE("widget: ButtonSetSpecs", "[ui]") TEST_CASE("widget: ButtonSetState", "[ui]") { - moci::Button button {""}; + moci::Button button{""}; REQUIRE(button.getState() == moci::ButtonState::Normal); button.SetState(moci::ButtonState::Down); @@ -77,14 +77,13 @@ TEST_CASE("widget: ButtonSetState", "[ui]") TEST_CASE("widget: ButtonCallbackStateChanged", "[ui]") { auto wasCalled = false; - auto specs = moci::ButtonSpecs {}; - specs.callbacks.stateChanged = [&](auto state) - { + auto specs = moci::ButtonSpecs{}; + specs.callbacks.stateChanged = [&](auto state) { REQUIRE(state == moci::ButtonState::Down); wasCalled = true; }; - auto slider = moci::Button {"test", specs}; + auto slider = moci::Button{"test", specs}; REQUIRE(slider.getState() == moci::ButtonState::Normal); slider.SetState(moci::ButtonState::Down); REQUIRE(slider.getState() == moci::ButtonState::Down); @@ -94,8 +93,8 @@ TEST_CASE("widget: ButtonCallbackStateChanged", "[ui]") TEST_CASE("widget: ButtonCallbackStateChangedCallbackNotSet", "[ui]") { auto wasCalled = false; - auto specs = moci::ButtonSpecs {}; - auto slider = moci::Button {"test", specs}; + auto specs = moci::ButtonSpecs{}; + auto slider = moci::Button{"test", specs}; REQUIRE(slider.getState() == moci::ButtonState::Normal); slider.SetState(moci::ButtonState::Down); REQUIRE(slider.getState() == moci::ButtonState::Down); diff --git a/src/moci/widgets/component/component.cpp b/src/moci/widgets/component/component.cpp index ed0df34..11ea069 100644 --- a/src/moci/widgets/component/component.cpp +++ b/src/moci/widgets/component/component.cpp @@ -2,25 +2,28 @@ #include -namespace moci -{ +namespace moci { -Component::Component(std::string id) : _id(std::move(id)) { } +Component::Component(std::string id) : _id(std::move(id)) {} void Component::onDraw(Painter& painter) { ignoreUnused(painter); } -void Component::onResize() { } +void Component::onResize() {} void Component::draw(Painter& painter) { onDraw(painter); - for (auto* child : _children) { child->draw(painter); } + for (auto* child : _children) { + child->draw(painter); + } } void Component::resize() { onResize(); - for (auto* child : _children) { child->onResize(); } + for (auto* child : _children) { + child->onResize(); + } } void Component::setId(std::string id) { _id = std::move(id); } @@ -33,7 +36,9 @@ auto Component::getParent() -> Component* { return _parent; } auto Component::getRootComponent() -> Component* { - if (_parent != nullptr) { return _parent->getRootComponent(); } + if (_parent != nullptr) { + return _parent->getRootComponent(); + } return this; } @@ -43,7 +48,10 @@ void Component::addChild(Component* child) child->setParent(this); } -auto Component::getChildren() const noexcept -> std::vector const& { return _children; } +auto Component::getChildren() const noexcept -> std::vector const& +{ + return _children; +} void Component::setPosition(int x, int y) noexcept { @@ -82,9 +90,10 @@ auto Component::getBounds() const noexcept -> Rectangle { return _bounds; } auto Component::contains(Point position) const noexcept -> bool { - if (position.getX() >= getX() && position.getX() <= getX() + getWidth()) - { - if (position.getY() >= getY() && position.getY() <= getY() + getHeight()) { return true; } + if (position.getX() >= getX() && position.getX() <= getX() + getWidth()) { + if (position.getY() >= getY() && position.getY() <= getY() + getHeight()) { + return true; + } } return false; @@ -92,13 +101,15 @@ auto Component::contains(Point position) const noexcept -> bool auto Component::findComponentAt(Point position) noexcept -> Component* { - if (!contains(position)) { return nullptr; } + if (!contains(position)) { + return nullptr; + } - for (auto* comp : getChildren()) - { - if (comp->contains(position)) - { - if (comp->getChildren().empty()) { return comp; } + for (auto* comp : getChildren()) { + if (comp->contains(position)) { + if (comp->getChildren().empty()) { + return comp; + } return comp->findComponentAt(position); } @@ -112,12 +123,15 @@ void Component::setStyle(Style* newStyle) noexcept { _style = newStyle; } auto Component::getStyle() const noexcept -> Style* { // If style is set local - if (_style != nullptr) { return _style; } + if (_style != nullptr) { + return _style; + } // Style set on any parent - if (_parent != nullptr) - { - if (auto* parentStyle = _parent->getStyle(); parentStyle != nullptr) { return parentStyle; } + if (_parent != nullptr) { + if (auto* parentStyle = _parent->getStyle(); parentStyle != nullptr) { + return parentStyle; + } } // No style set diff --git a/src/moci/widgets/component/component.hpp b/src/moci/widgets/component/component.hpp index 245eae6..231a89e 100644 --- a/src/moci/widgets/component/component.hpp +++ b/src/moci/widgets/component/component.hpp @@ -11,8 +11,7 @@ #include #include -namespace moci -{ +namespace moci { class Style; @@ -160,11 +159,11 @@ class Component : public MouseCallback [[nodiscard]] auto getStyle() const noexcept -> Style*; private: - std::string _id {}; - Component* _parent {nullptr}; - std::vector _children {}; - Rectangle _bounds {}; - Style* _style {nullptr}; + std::string _id{}; + Component* _parent{nullptr}; + std::vector _children{}; + Rectangle _bounds{}; + Style* _style{nullptr}; }; } // namespace moci diff --git a/src/moci/widgets/component/component.test.cpp b/src/moci/widgets/component/component.test.cpp index 1689dac..33e7c8a 100644 --- a/src/moci/widgets/component/component.test.cpp +++ b/src/moci/widgets/component/component.test.cpp @@ -9,7 +9,7 @@ TEST_CASE("widget: ComponentDefaultConstruct", "[ui]") { - moci::Component c {}; + moci::Component c{}; REQUIRE(c.getWidth() == 0); REQUIRE(c.getHeight() == 0); REQUIRE(c.getId().empty()); @@ -19,7 +19,7 @@ TEST_CASE("widget: ComponentDefaultConstruct", "[ui]") TEST_CASE("widget: ComponentIDConstruct", "[ui]") { - moci::Component c {"test"}; + moci::Component c{"test"}; REQUIRE(c.getWidth() == 0); REQUIRE(c.getHeight() == 0); REQUIRE(c.getId() == "test"); @@ -29,7 +29,7 @@ TEST_CASE("widget: ComponentIDConstruct", "[ui]") TEST_CASE("widget: ComponentSetID", "[ui]") { - moci::Component c1 {}; + moci::Component c1{}; REQUIRE(c1.getId().empty()); c1.setId("test"); REQUIRE(c1.getId() == "test"); @@ -37,8 +37,8 @@ TEST_CASE("widget: ComponentSetID", "[ui]") TEST_CASE("widget: ComponentSetParent", "[ui]") { - moci::Component c1 {}; - moci::Component c2 {}; + moci::Component c1{}; + moci::Component c2{}; REQUIRE(c1.getParent() == nullptr); REQUIRE(c2.getParent() == nullptr); c1.setParent(&c2); @@ -47,9 +47,9 @@ TEST_CASE("widget: ComponentSetParent", "[ui]") TEST_CASE("widget: ComponentGetRootComponent", "[ui]") { - moci::Component c1 {}; - moci::Component c2 {}; - moci::Component c3 {}; + moci::Component c1{}; + moci::Component c2{}; + moci::Component c3{}; c2.setParent(&c1); c3.setParent(&c2); REQUIRE(c3.getRootComponent() == &c1); @@ -57,8 +57,8 @@ TEST_CASE("widget: ComponentGetRootComponent", "[ui]") TEST_CASE("widget: ComponentAddChild", "[ui]") { - moci::Component c1 {}; - moci::Component c2 {}; + moci::Component c1{}; + moci::Component c2{}; REQUIRE(c1.getChildren().empty()); c1.addChild(&c2); REQUIRE(c1.getChildren().size() == 1); @@ -67,7 +67,7 @@ TEST_CASE("widget: ComponentAddChild", "[ui]") TEST_CASE("widget: ComponentSetSize", "[ui]") { - moci::Component c {}; + moci::Component c{}; c.setSize(100, 50); REQUIRE(c.getWidth() == 100); REQUIRE(c.getHeight() == 50); @@ -75,7 +75,7 @@ TEST_CASE("widget: ComponentSetSize", "[ui]") TEST_CASE("widget: ComponentSetPositionXY", "[ui]") { - moci::Component c {}; + moci::Component c{}; c.setPosition(100, 50); REQUIRE(c.getX() == 100); REQUIRE(c.getY() == 50); @@ -83,7 +83,7 @@ TEST_CASE("widget: ComponentSetPositionXY", "[ui]") TEST_CASE("widget: ComponentSetPositionPoint", "[ui]") { - moci::Component c {}; + moci::Component c{}; c.setPosition({100, 50}); REQUIRE(c.getX() == 100); REQUIRE(c.getY() == 50); @@ -91,7 +91,7 @@ TEST_CASE("widget: ComponentSetPositionPoint", "[ui]") TEST_CASE("widget: ComponentSetBounds", "[ui]") { - moci::Component c {}; + moci::Component c{}; c.setBounds({100, 50, 10, 20}); auto bounds = c.getBounds(); REQUIRE(bounds.getX() == 100); @@ -102,7 +102,7 @@ TEST_CASE("widget: ComponentSetBounds", "[ui]") TEST_CASE("widget: ComponentContains", "[ui]") { - moci::Component c {}; + moci::Component c{}; c.setBounds({100, 50, 10, 20}); REQUIRE(c.contains({0, 0}) == false); REQUIRE(c.contains({110, 49}) == false); @@ -111,11 +111,11 @@ TEST_CASE("widget: ComponentContains", "[ui]") TEST_CASE("widget: ComponentFindComponentAt", "[ui]") { - auto area = moci::Rectangle {0, 0, 100, 100}; - auto parent = moci::Component {}; - auto c1 = moci::Component {}; - auto c2 = moci::Component {}; - auto c3 = moci::Component {}; + auto area = moci::Rectangle{0, 0, 100, 100}; + auto parent = moci::Component{}; + auto c1 = moci::Component{}; + auto c2 = moci::Component{}; + auto c3 = moci::Component{}; parent.setBounds(area); parent.addChild(&c1); @@ -134,17 +134,17 @@ TEST_CASE("widget: ComponentFindComponentAt", "[ui]") TEST_CASE("widget: ComponentStyle", "[ui]") { - moci::Component c {}; + moci::Component c{}; REQUIRE(c.getStyle() == nullptr); c.setStyle(nullptr); REQUIRE(c.getStyle() == nullptr); - moci::Style style {}; + moci::Style style{}; c.setStyle(&style); REQUIRE(c.getStyle() == &style); - moci::Component child {}; + moci::Component child{}; c.addChild(&child); REQUIRE(child.getStyle() == &style); } diff --git a/src/moci/widgets/component/label.cpp b/src/moci/widgets/component/label.cpp index 04b4d2e..3b2f779 100644 --- a/src/moci/widgets/component/label.cpp +++ b/src/moci/widgets/component/label.cpp @@ -2,14 +2,18 @@ #include -namespace moci -{ -Label::Label(std::string text, ColorRGBA32 col) : Component("label"), _text(std::move(text)), _color(col) { } +namespace moci { +Label::Label(std::string text, ColorRGBA32 col) + : Component("label") + , _text(std::move(text)) + , _color(col) +{} void Label::onDraw(Painter& painter) { auto* style = getStyle(); - // If yo hit this assertion, you probably forgot to set the style on the top level component. + // If yo hit this assertion, you probably forgot to set the style on the top level + // component. MOCI_CORE_ASSERT(style != nullptr, "Style should not be null"); style->drawLabel(painter, getBounds(), *this); } diff --git a/src/moci/widgets/component/label.hpp b/src/moci/widgets/component/label.hpp index f701e9a..f514b57 100644 --- a/src/moci/widgets/component/label.hpp +++ b/src/moci/widgets/component/label.hpp @@ -4,9 +4,9 @@ #include -namespace moci -{ +namespace moci { class Label; + class LabelStyleMethods { public: @@ -24,14 +24,17 @@ class Label : public Component auto onDraw(Painter& painter) -> void override; auto setText(std::string newText) -> void { _text = std::move(newText); } + [[nodiscard]] auto getText() const noexcept -> std::string const& { return _text; } + [[nodiscard]] auto getTextView() const noexcept -> std::string_view { return _text; } void setTextColor(ColorRGBA32 col) noexcept { _color = col; } + [[nodiscard]] auto getTextColor() const noexcept -> ColorRGBA32 { return _color; } private: - std::string _text {}; - ColorRGBA32 _color {}; + std::string _text{}; + ColorRGBA32 _color{}; }; } // namespace moci diff --git a/src/moci/widgets/component/label.test.cpp b/src/moci/widgets/component/label.test.cpp index 42c10ef..48e6f44 100644 --- a/src/moci/widgets/component/label.test.cpp +++ b/src/moci/widgets/component/label.test.cpp @@ -10,14 +10,14 @@ TEST_CASE("widget: LabelConstruct", "[ui]") { - moci::Label const label {"test", {}}; + moci::Label const label{"test", {}}; REQUIRE(label.getText() == "test"); REQUIRE(label.getTextView() == "test"); } TEST_CASE("widget: LabelSetText", "[ui]") { - moci::Label label {"", {}}; + moci::Label label{"", {}}; REQUIRE(label.getText().empty()); REQUIRE(label.getTextView().empty()); label.setText("test143"); @@ -27,7 +27,7 @@ TEST_CASE("widget: LabelSetText", "[ui]") TEST_CASE("widget: LabelSetTextColor", "[ui]") { - moci::Label label {"", {}}; + moci::Label label{"", {}}; auto c1 = label.getTextColor(); REQUIRE(c1.red() == 0.0F); diff --git a/src/moci/widgets/component/slider.cpp b/src/moci/widgets/component/slider.cpp index 4f019a2..d4badf5 100644 --- a/src/moci/widgets/component/slider.cpp +++ b/src/moci/widgets/component/slider.cpp @@ -2,17 +2,18 @@ #include -namespace moci -{ +namespace moci { Slider::Slider(ColorRGBA32 col, SliderCallbacks callbacks) - : Component("slider"), _callbacks(std::move(callbacks)), _color(col) -{ -} + : Component("slider") + , _callbacks(std::move(callbacks)) + , _color(col) +{} void Slider::onDraw(Painter& painter) { auto* style = getStyle(); - // If yo hit this assertion, you probably forgot to set the style on the top level component. + // If yo hit this assertion, you probably forgot to set the style on the top level + // component. MOCI_CORE_ASSERT(style != nullptr, "Style should not be null"); style->drawSlider(painter, getBounds(), *this); } @@ -39,10 +40,13 @@ auto Slider::getValue() const noexcept -> float { return _value; } auto Slider::setValue(float newValue) noexcept -> void { _value = newValue; - if (_callbacks.valueChanged) { _callbacks.valueChanged(newValue); } + if (_callbacks.valueChanged) { + _callbacks.valueChanged(newValue); + } } auto Slider::getColor() const noexcept -> ColorRGBA32 { return _color; } + void Slider::setColor(ColorRGBA32 col) noexcept { _color = col; } } // namespace moci diff --git a/src/moci/widgets/component/slider.hpp b/src/moci/widgets/component/slider.hpp index 4b1923a..f47acfb 100644 --- a/src/moci/widgets/component/slider.hpp +++ b/src/moci/widgets/component/slider.hpp @@ -5,10 +5,10 @@ #include #include -namespace moci -{ +namespace moci { class Slider; + struct SliderCallbacks { std::function valueChanged = {}; @@ -19,13 +19,14 @@ class SliderStyleMethods public: virtual ~SliderStyleMethods() = default; - virtual void drawSlider(Painter& painter, Rectangle bounds, Slider const& slider) = 0; + virtual void drawSlider(Painter& painter, Rectangle bounds, Slider const& slider) + = 0; }; class Slider : public Component { public: - explicit Slider(ColorRGBA32 col, SliderCallbacks callbacks = SliderCallbacks {}); + explicit Slider(ColorRGBA32 col, SliderCallbacks callbacks = SliderCallbacks{}); ~Slider() override = default; auto onDraw(Painter& painter) -> void override; diff --git a/src/moci/widgets/component/slider.test.cpp b/src/moci/widgets/component/slider.test.cpp index b5b1386..7784c54 100644 --- a/src/moci/widgets/component/slider.test.cpp +++ b/src/moci/widgets/component/slider.test.cpp @@ -11,13 +11,13 @@ TEST_CASE("widget: SliderConstruct", "[ui]") { - moci::Slider const slider {moci::Colors::black}; + moci::Slider const slider{moci::Colors::black}; REQUIRE(slider.getValue() == 0.0F); } TEST_CASE("widget: SliderSetValue", "[ui]") { - moci::Slider slider {moci::Colors::black}; + moci::Slider slider{moci::Colors::black}; REQUIRE(slider.getValue() == 0.0F); slider.setValue(143.0F); REQUIRE(slider.getValue() == 143.0F); @@ -25,7 +25,7 @@ TEST_CASE("widget: SliderSetValue", "[ui]") TEST_CASE("widget: SliderSetColor", "[ui]") { - moci::Slider slider {{}}; + moci::Slider slider{{}}; auto c1 = slider.getColor(); REQUIRE(c1.red() == 0.0F); @@ -45,14 +45,13 @@ TEST_CASE("widget: SliderSetColor", "[ui]") TEST_CASE("widget: SliderCallbackValueChanged", "[ui]") { auto wasCalled = false; - auto callbacks = moci::SliderCallbacks {}; - callbacks.valueChanged = [&](auto val) - { + auto callbacks = moci::SliderCallbacks{}; + callbacks.valueChanged = [&](auto val) { REQUIRE(val == 143.0F); wasCalled = true; }; - auto slider = moci::Slider {moci::Colors::black, callbacks}; + auto slider = moci::Slider{moci::Colors::black, callbacks}; REQUIRE(slider.getValue() == 0.0F); slider.setValue(143.0F); REQUIRE(slider.getValue() == 143.0F); @@ -62,8 +61,8 @@ TEST_CASE("widget: SliderCallbackValueChanged", "[ui]") TEST_CASE("widget: SliderCallbackValueChangedCallbackNotSet", "[ui]") { auto wasCalled = false; - auto callbacks = moci::SliderCallbacks {}; - auto slider = moci::Slider {moci::Colors::black, callbacks}; + auto callbacks = moci::SliderCallbacks{}; + auto slider = moci::Slider{moci::Colors::black, callbacks}; REQUIRE(slider.getValue() == 0.0F); slider.setValue(143.0F); REQUIRE(slider.getValue() == 143.0F); @@ -72,16 +71,16 @@ TEST_CASE("widget: SliderCallbackValueChangedCallbackNotSet", "[ui]") TEST_CASE("widget: SliderMouseScrolled", "[ui]") { - auto callbacks = moci::SliderCallbacks {}; - auto slider = moci::Slider {moci::Colors::black, callbacks}; + auto callbacks = moci::SliderCallbacks{}; + auto slider = moci::Slider{moci::Colors::black, callbacks}; slider.setValue(0.5F); REQUIRE(slider.getValue() == 0.5F); - slider.mouseScrolled(moci::MouseScrolledEvent {0.0F, 1.0F}); + slider.mouseScrolled(moci::MouseScrolledEvent{0.0F, 1.0F}); REQUIRE(slider.getValue() == Catch::Approx(0.55F)); slider.setValue(1.0F); REQUIRE(slider.getValue() == 1.0F); - slider.mouseScrolled(moci::MouseScrolledEvent {0.0F, -1.0F}); + slider.mouseScrolled(moci::MouseScrolledEvent{0.0F, -1.0F}); REQUIRE(slider.getValue() == Catch::Approx(0.95F)); } diff --git a/src/moci/widgets/layer/component_layer.cpp b/src/moci/widgets/layer/component_layer.cpp index f69a262..93284a5 100644 --- a/src/moci/widgets/layer/component_layer.cpp +++ b/src/moci/widgets/layer/component_layer.cpp @@ -1,7 +1,6 @@ #include "component_layer.hpp" -namespace moci -{ +namespace moci { void ComponentLayer::onAttach() { MOCI_PROFILE_FUNCTION(); @@ -41,11 +40,13 @@ void ComponentLayer::onImGuiRender() void ComponentLayer::onEvent(Event& e) { MOCI_PROFILE_FUNCTION(); - auto dispatcher = EventDispatcher {e}; + auto dispatcher = EventDispatcher{e}; dispatcher.dispatch([this](auto& e) { return onWindowResized(e); }); dispatcher.dispatch([this](auto& e) { return onMouseMoved(e); }); dispatcher.dispatch([this](auto& e) { return onMouseScrolled(e); }); - dispatcher.dispatch([this](auto& e) { return onMousePressed(e); }); + dispatcher.dispatch([this](auto& e) { + return onMousePressed(e); + }); } auto ComponentLayer::onWindowResized(WindowResizeEvent& e) -> bool @@ -75,7 +76,9 @@ auto ComponentLayer::onMousePressed(MouseButtonPressedEvent& e) -> bool ignoreUnused(e); auto const x = static_cast(Input::getMouseX()); auto const y = static_cast(Input::getMouseY()); - return handleEvent([&](auto* comp) { return comp->mouseClicked(MouseCallback::Click {x, y}); }); + return handleEvent([&](auto* comp) { + return comp->mouseClicked(MouseCallback::Click{x, y}); + }); } } // namespace moci diff --git a/src/moci/widgets/layer/component_layer.hpp b/src/moci/widgets/layer/component_layer.hpp index 2bd35bc..5f24ab2 100644 --- a/src/moci/widgets/layer/component_layer.hpp +++ b/src/moci/widgets/layer/component_layer.hpp @@ -11,13 +11,16 @@ #include "imgui.h" -namespace moci -{ +namespace moci { class ComponentLayer : public Layer { public: - explicit ComponentLayer(std::unique_ptr&& root) : Layer("component-layer"), _rootComponent(std::move(root)) { } + explicit ComponentLayer(std::unique_ptr&& root) + : Layer("component-layer") + , _rootComponent(std::move(root)) + {} + ~ComponentLayer() override = default; void onAttach() override; @@ -45,10 +48,11 @@ class ComponentLayer : public Layer } MOCI_CORE_ASSERT(comp, "Should never be null"); - while (!handler(comp)) - { + while (!handler(comp)) { comp = comp->getParent(); - if (comp == nullptr) { return false; } + if (comp == nullptr) { + return false; + } } return true; @@ -57,8 +61,8 @@ class ComponentLayer : public Layer float _width = 1280.0F; float _height = 1024.0F; - std::unique_ptr _renderQueue {}; - Style _defaultStyle {}; + std::unique_ptr _renderQueue{}; + Style _defaultStyle{}; std::unique_ptr _rootComponent; }; } // namespace moci diff --git a/src/moci/widgets/style/style.cpp b/src/moci/widgets/style/style.cpp index 9acf24b..4b791e2 100644 --- a/src/moci/widgets/style/style.cpp +++ b/src/moci/widgets/style/style.cpp @@ -1,48 +1,53 @@ #include -namespace moci -{ +namespace moci { void Style::drawButton(Painter& painter, Rectangle bounds, Button const& button) { auto area = bounds; auto const width = area.getWidth(); auto const height = area.getHeight(); auto const border = std::max(1, static_cast(height * 0.1)); - auto const bottomLeftCorner = Point {area.getX(), area.getY()}; + auto const bottomLeftCorner = Point{area.getX(), area.getY()}; auto const color = button.getTextColor(); // left - auto const leftEdge = Rectangle {bottomLeftCorner, border, area.getHeight()}; + auto const leftEdge = Rectangle{bottomLeftCorner, border, area.getHeight()}; painter.drawQuad(leftEdge.toFloat(), color); // right - auto const rightEdge = Rectangle { - {bottomLeftCorner.getX() + width - border, bottomLeftCorner.getY()}, // - border, // - area.getHeight() // + auto const rightEdge = Rectangle{ + {bottomLeftCorner.getX() + width - border, bottomLeftCorner.getY()}, // + border, // + area.getHeight() // }; painter.drawQuad(rightEdge.toFloat(), color); // bottom - auto const bottomEdge = Rectangle {bottomLeftCorner, area.getWidth(), border}; + auto const bottomEdge = Rectangle{bottomLeftCorner, area.getWidth(), border}; painter.drawQuad(bottomEdge.toFloat(), color); // top - auto const topEdge = Rectangle { - {bottomLeftCorner.getX(), bottomLeftCorner.getY() + height - border}, // - width, // - border // + auto const topEdge = Rectangle{ + {bottomLeftCorner.getX(), bottomLeftCorner.getY() + height - border}, // + width, // + border // }; painter.drawQuad(topEdge.toFloat(), color); // text - painter.drawText(button.getText(), {bounds.getX() + width / 2, bounds.getY() + height}, 0.5F, color); + painter.drawText( + button.getText(), + {bounds.getX() + width / 2, bounds.getY() + height}, + 0.5F, + color + ); } void Style::drawLabel(Painter& painter, Rectangle bounds, Label const& label) { auto area = bounds; - painter.drawText(label.getText(), {area.getX(), area.getY()}, 0.5F, label.getTextColor()); + painter + .drawText(label.getText(), {area.getX(), area.getY()}, 0.5F, label.getTextColor()); } void Style::drawSlider(Painter& painter, Rectangle bounds, Slider const& slider) @@ -51,40 +56,42 @@ void Style::drawSlider(Painter& painter, Rectangle bounds, Slider const& sl auto const width = area.getWidth(); auto const height = area.getHeight(); auto const border = std::max(1, static_cast(height * 0.1)); - auto const bottomLeftCorner = Point {area.getX(), area.getY()}; + auto const bottomLeftCorner = Point{area.getX(), area.getY()}; auto const color = slider.getColor(); // left - auto const leftEdge = Rectangle {bottomLeftCorner, border, area.getHeight()}; + auto const leftEdge = Rectangle{bottomLeftCorner, border, area.getHeight()}; painter.drawQuad(leftEdge.toFloat(), color); // right - auto const rightEdge = Rectangle { - {bottomLeftCorner.getX() + width - border, bottomLeftCorner.getY()}, // - border, // - area.getHeight() // + auto const rightEdge = Rectangle{ + {bottomLeftCorner.getX() + width - border, bottomLeftCorner.getY()}, // + border, // + area.getHeight() // }; painter.drawQuad(rightEdge.toFloat(), color); // bottom - auto const bottomEdge = Rectangle {bottomLeftCorner, area.getWidth(), border}; + auto const bottomEdge = Rectangle{bottomLeftCorner, area.getWidth(), border}; painter.drawQuad(bottomEdge.toFloat(), color); // top - auto const topEdge = Rectangle { - {bottomLeftCorner.getX(), bottomLeftCorner.getY() + height - border}, // - width, // - border // + auto const topEdge = Rectangle{ + {bottomLeftCorner.getX(), bottomLeftCorner.getY() + height - border}, // + width, // + border // }; painter.drawQuad(topEdge.toFloat(), color); // infill - auto const inFillWidth - = static_cast(static_cast(width - border * 4) * std::min(slider.getValue(), 1.0F)); - auto const inFill = Rectangle { - {bottomLeftCorner.getX() + (border * 2), bottomLeftCorner.getY() + (border * 2)}, // - inFillWidth, // - height - (border * 4) // + auto const inFillWidth = static_cast( + static_cast(width - border * 4) * std::min(slider.getValue(), 1.0F) + ); + auto const inFill = Rectangle{ + {bottomLeftCorner.getX() + (border * 2), bottomLeftCorner.getY() + (border * 2) + }, // + inFillWidth, // + height - (border * 4) // }; painter.drawQuad(inFill.toFloat(), color); } diff --git a/src/moci/widgets/style/style.hpp b/src/moci/widgets/style/style.hpp index 532c90d..da0581b 100644 --- a/src/moci/widgets/style/style.hpp +++ b/src/moci/widgets/style/style.hpp @@ -4,8 +4,7 @@ #include #include -namespace moci -{ +namespace moci { class Style : public ButtonStyleMethods , public LabelStyleMethods