Compare commits

..

25 Commits
dev ... main

Author SHA1 Message Date
anulax1225 fffa1b81e9 Little modif ago%!(EXTRA string=7 months)
anulax1225 7a6c7d58c6 Next step ago%!(EXTRA string=8 months)
anulax1225 b2ebd91bec Adding stb lib ago%!(EXTRA string=8 months)
anulax1225 554bbe6567 Commit before texture adding ago%!(EXTRA string=8 months)
anulax1225 650e4584bd Io ago%!(EXTRA string=8 months)
anulax1225 b17c794999 Gros boulo dans son cul ago%!(EXTRA string=8 months)
anulax1225 0ef47947fb Putting imgui docking and no dicking version ago%!(EXTRA string=8 months)
Ambigapathy Vinayak 8778689229 Fixed Imgui window disabled if in main window ago%!(EXTRA string=12 months)
anulax1225 518ca85c85 Cleaned up ago%!(EXTRA string=12 months)
anulax1225 b61777f5d7 Working Imgui layer ago%!(EXTRA string=12 months)
anulax1225 5959834aca Cleaned up ago%!(EXTRA string=12 months)
anulax1225 90b04a50ef Ordered io codes ago%!(EXTRA string=12 months)
anulax1225 06a1c6c246 Setup for Imgui ago%!(EXTRA string=12 months)
anulax1225 d40fa774c1 Cleaned up project and ajusted window interface ago%!(EXTRA string=12 months)
Ambigapathy Vinayak e65aa30c31 Modified layers and layerstack system ago%!(EXTRA string=12 months)
Ambigapathy Vinayak 1698fd5176 Fixed build error on windows debug and release ago%!(EXTRA string=12 months)
anulax1225 1f704b70d7 Cleaned up code ago%!(EXTRA string=12 months)
anulax1225 b24ab05c8f Added debug build options ago%!(EXTRA string=12 months)
anulax1225 20994a3a9a Change deps file ago%!(EXTRA string=12 months)
anulax1225 0144cf171e
Update README.md ago%!(EXTRA string=12 months)
anulax1225 d6addb993e fixed build ago%!(EXTRA string=1 year)
anulax1225 4961e461bc fixed build ago%!(EXTRA string=1 year)
anulax1225 d271f9422e Added bakatools dep to bakara ago%!(EXTRA string=1 year)
anulax1225 c7f7932d2f Fixed error in dependencie file ago%!(EXTRA string=1 year)
anulax1225 9d782283f9 Added bakasable config ago%!(EXTRA string=1 year)
  1. 12
      .gitmodules
  2. 45
      README.md
  3. 95
      bakara/premake5.lua
  4. 24
      bakara/src/bakara.h
  5. 49
      bakara/src/bakara/core/application.cpp
  6. 32
      bakara/src/bakara/core/assert.h
  7. 25
      bakara/src/bakara/core/base.h
  8. 23
      bakara/src/bakara/core/entry.cpp
  9. 20
      bakara/src/bakara/core/layer.h
  10. 50
      bakara/src/bakara/core/layer_stack.cpp
  11. 29
      bakara/src/bakara/core/layer_stack.h
  12. 28
      bakara/src/bakara/core/log.cpp
  13. 47
      bakara/src/bakara/core/log.h
  14. 32
      bakara/src/bakara/imgui/imgui_layer.cpp
  15. 23
      bakara/src/bakara/imgui/imgui_layer.h
  16. 8
      bakara/src/bakara/math/mathpch.h
  17. 47
      bakara/src/bakara/plaforms/window/glfw/win_glfw.h
  18. 65
      bakara/src/bakara/tools/string_fmt.h
  19. 21
      bakara/src/bkpch.h
  20. 311
      bakara/vendor/glad/include/KHR/khrplatform.h
  21. 4137
      bakara/vendor/glad/include/glad/glad.h
  22. 2129
      bakara/vendor/glad/src/glad.c
  23. 1
      bakara/vendor/glfw
  24. 1
      bakara/vendor/glm
  25. 1
      bakara/vendor/imgui
  26. 157
      bakara/vendor/premake5.lua
  27. 1
      bakara/vendor/spdloglib
  28. 57
      build.sh
  29. 11
      dependencies
  30. 32
      examples/test_imgui.cpp
  31. 23
      examples/test_layer.cpp
  32. 30
      manual/index.md
  33. 45
      package.json
  34. 112
      premake5.lua
  35. 59
      sandbox/premake5.lua
  36. 37
      src/bakara.h
  37. 73
      src/bakara/core/application.cpp
  38. 62
      src/bakara/core/application.h
  39. 17
      src/bakara/core/deltatime.h
  40. 21
      src/bakara/core/entry.cpp
  41. 0
      src/bakara/core/layer.cpp
  42. 23
      src/bakara/core/layer.h
  43. 50
      src/bakara/core/layer_stack.cpp
  44. 31
      src/bakara/core/layer_stack.h
  45. 70
      src/bakara/core/window.h
  46. 0
      src/bakara/events/app_event.h
  47. 28
      src/bakara/events/dispacher.h
  48. 48
      src/bakara/events/event.h
  49. 0
      src/bakara/events/events.h
  50. 19
      src/bakara/events/key_event.h
  51. 22
      src/bakara/events/mouse_event.h
  52. 12
      src/bakara/events/window_event.h
  53. 5
      src/bakara/imgui/imgui_build.cpp
  54. 77
      src/bakara/imgui/imgui_layer.cpp
  55. 18
      src/bakara/imgui/imgui_layer.h
  56. 18
      src/bakara/io/controller.h
  57. 47
      src/bakara/io/controller_codes.h
  58. 10
      src/bakara/io/io_codes.h
  59. 84
      src/bakara/io/key_codes.h
  60. 14
      src/bakara/io/keyboard.h
  61. 15
      src/bakara/io/mouse.h
  62. 30
      src/bakara/io/mouse_codes.h
  63. 15
      src/bakara/math/types.h
  64. 30
      src/bakara/renderer/buffer.cpp
  65. 27
      src/bakara/renderer/buffer.h
  66. 56
      src/bakara/renderer/buffer_layout.cpp
  67. 70
      src/bakara/renderer/buffer_layout.h
  68. 29
      src/bakara/renderer/cameras/ortho_camera.cpp
  69. 31
      src/bakara/renderer/cameras/ortho_camera.h
  70. 76
      src/bakara/renderer/cameras/ortho_camera_controller.cpp
  71. 41
      src/bakara/renderer/cameras/ortho_camera_controller.h
  72. 18
      src/bakara/renderer/graphics_context.cpp
  73. 15
      src/bakara/renderer/graphics_context.h
  74. 8
      src/bakara/renderer/render_command.cpp
  75. 20
      src/bakara/renderer/render_command.h
  76. 39
      src/bakara/renderer/renderer.cpp
  77. 38
      src/bakara/renderer/renderer.h
  78. 81
      src/bakara/renderer/renderer2D.cpp
  79. 33
      src/bakara/renderer/renderer2D.h
  80. 17
      src/bakara/renderer/renderer_api.h
  81. 60
      src/bakara/renderer/shader.cpp
  82. 49
      src/bakara/renderer/shader.h
  83. 18
      src/bakara/renderer/texture.cpp
  84. 22
      src/bakara/renderer/texture.h
  85. 18
      src/bakara/renderer/vertex_array.cpp
  86. 21
      src/bakara/renderer/vertex_array.h
  87. 4
      src/platforms/glfw/glfw_controller.cpp
  88. 35
      src/platforms/glfw/glfw_controller.h
  89. 27
      src/platforms/glfw/glfw_keyboard.cpp
  90. 36
      src/platforms/glfw/glfw_mouse.cpp
  91. 114
      src/platforms/glfw/glfw_window.cpp
  92. 51
      src/platforms/glfw/glfw_window.h
  93. 56
      src/platforms/opengl/opengl_buffer.cpp
  94. 35
      src/platforms/opengl/opengl_buffer.h
  95. 33
      src/platforms/opengl/opengl_context.cpp
  96. 20
      src/platforms/opengl/opengl_context.h
  97. 28
      src/platforms/opengl/opengl_renderer_api.cpp
  98. 17
      src/platforms/opengl/opengl_renderer_api.h
  99. 158
      src/platforms/opengl/opengl_shader.cpp
  100. 38
      src/platforms/opengl/opengl_shader.h
  101. Some files were not shown because too many files have changed in this diff Show More

12
.gitmodules vendored

@ -1,12 +0,0 @@
[submodule "bakara/vendor/glm"]
path = bakara/vendor/glm
url = https://github.com/g-truc/glm.git
[submodule "bakara/vendor/spdloglib"]
path = bakara/vendor/spdloglib
url = https://github.com/gabime/spdlog
[submodule "bakara/vendor/glfw"]
path = bakara/vendor/glfw
url = https://github.com/glfw/glfw
[submodule "bakara/vendor/imgui"]
path = bakara/vendor/imgui
url = https://github.com/ocornut/imgui

@ -1,48 +1,5 @@
# Bakara project
## Generate doc
To generate the documentation using doxygen, <a>install</a> it from there website for your plaform.
Then write commands :
```bash
cd dirs/to/bakara
doxygen
```
# Baka Rasterazed Artwork
## Prerequiste
* A video/graphics card that supports OpenGL.
### Windows
* C++ ms-compiler for Windows
### Linux
* GCC compiler suite.
## Build
### Windows
On windows, write commands :
```batch
cd C:\Users\username
git clone https://github.com/anulax/bakara
git submodule init
git submodule update
.\vendor\premake5 vs2022
dotnet build
dotnet run
```
Or use visual studio 2022 to build your project.
### Linux
---
On linux (if you don't have premake5, install it with your distro's packet manager). You have two env variable to change build proccess :
| Name | Value | Description |
| ----------- | ----------- | ----------- |
| exec | 0/1 | Lauch app |
| clear | 0/1 | Remove bin |
Then write commands :
```bash
cd ~/
git clone https://github.com/anulax/bakara
git submodule init
git submodule update
(export clear=1 autoexec=1)
./build.sh config=release
```

@ -1,95 +0,0 @@
project "bakara"
language "C++"
cppdialect "C++17"
targetdir("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"vendor/glm/glm/**.hpp",
"vendor/glm/glm/**.inl",
"vendor/imgui/misc/cpp/imgui_stdlib.cpp",
"vendor/imgui/backends/imgui_impl_opengl3.cpp",
"vendor/imgui/backends/imgui_impl_glfw.cpp",
"src/**.h",
"src/**.cpp",
}
defines
{
"_CRT_SECURE_NO_WARNINGS",
"GLFW_INCLUDE_NONE",
"IMGUI_IMPL_OPENGL_LOADER_GLAD"
}
includedirs
{
"%{IncludeDirs.bakara}",
"%{IncludeDirs.glm}",
"%{IncludeDirs.spdlog}",
"%{IncludeDirs.glad}",
"%{IncludeDirs.glfw}",
"%{IncludeDirs.imgui}"
}
links
{
"GLFW",
"GLAD",
"ImGui"
}
filter "configurations:Debug"
defines
{
"BK_DEBUG",
"DEBUG"
}
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines
{
"BK_RELEASE",
"NDEBUG"
}
runtime "Release"
optimize "on"
filter "system:windows"
kind "StaticLib"
staticruntime "on"
defines
{
"BK_PLATFORM_WINDOWS"
}
links
{
"opengl32.lib"
}
filter "system:linux"
kind "SharedLib"
staticruntime "off"
files
{
"vendor/glm/glm/**.cpp"
}
defines
{
"BK_PLATFORM_LINUX"
}
links
{
"GL"
}

@ -1,24 +0,0 @@
#pragma once
/*! \file bakara.h
Precompiled headers for external pragrams.
*/
/*! \namespace Bk
Global namespace doc
*/
namespace Bk {}
/*! \namespace Bk::Plaform
Plaform namespace doc
*/
namespace Bk::Plaform {}
#include <bakara/math/type.h>
#include <bakara/core/log.h>
#include <bakara/core/assert.h>
#include <bakara/io/io_codes.h>
#include <bakara/events/events.h>
#include <bakara/core/application.h>
#include <bakara/core/layer.h>

@ -1,49 +0,0 @@
#include "application.h"
namespace Bk {
Application* Application::p_instance = nullptr;
Application::Application()
{
BK_CORE_MSG_ASSERT(p_instance == nullptr, "Application already exists, can not create two application.")
Application::p_instance = this;
h_window = std::shared_ptr<Window>(Window::create_window());
h_window->set_event_callback(BK_BIND_EVENT_FN(on_event));
p_running = true;
}
Application::~Application() { }
void Application::on_event(Event& e)
{
EventDispatcher dispatcher(e);
if (!(dispatcher.dispatch<WindowCloseEvent>(BK_BIND_DISPACHER_FN(WindowCloseEvent, on_window_close)) ||
dispatcher.dispatch<WindowResizeEvent>(BK_BIND_DISPACHER_FN(WindowResizeEvent, on_window_resize))))
{
for(auto it = p_layer_stack.rbegin(); it != p_layer_stack.rend(); it++)
{
(*it)->on_event(e);
}
}
}
bool Application::on_window_close(WindowCloseEvent& e)
{
h_window->close();
p_running = false;
return true;
}
bool Application::on_window_resize(WindowResizeEvent& e)
{
return true;
}
void Application::run()
{
while (p_running)
{
h_window->on_update();
}
}
}

@ -1,32 +0,0 @@
#pragma once
/*! \file assert.h
This file contains the assert macros. CORE macros musn't be used by the application.
*/
#include "base.h"
#include <bakara/tools/string_fmt.h>
#ifdef BK_ENABLE_ASSERT
/*! \def BK_CORE_VAMSG_ASSERT(check, msg, ...)
Assertes a condition, and throw an error with the formatted message as description
@param check : Condionne to assert
@param msg : format string error message
@param ... : variable arguments to put in the string
*/
#define BK_CORE_VAMSG_ASSERT(check, msg, ...) if(!(check)) { BK_CORE_ERROR(Tools::format("Assertion [%s] failed at %s:%d\n\tError : %s", BK_STRINGIFY(check), __FILE__, __LINE__, msg), __VA_ARGS__); BK_DEBUGBREAK(); }
#define BK_CORE_MSG_ASSERT(check, msg) if(!(check)) { BK_CORE_ERROR("Assertion [{0}] failed at {1}:{2}\n\tError : {3}", BK_STRINGIFY(check), __FILE__, __LINE__, msg); BK_DEBUGBREAK(); }
#define BK_CORE_ASSERT(check) if(!(check)) { BK_CORE_ERROR("Assertion [{0}] failed at {1}:{2}", BK_STRINGIFY(check), __FILE__, __LINE__); BK_DEBUGBREAK(); }
#define BK_VAMSG_ASSERT(check, msg, ...) if(!(check)) { BK_ERROR(Bk::Tools::format("Assertion [%s] failed at %s:%d\n\tError : %s", BK_STRINGIFY(check), __FILE__, __LINE__, msg), __VA_ARGS__); BK_DEBUGBREAK(); }
#define BK_MSG_ASSERT(check, msg) if(!(check)) { BK_ERROR("Assertion [{0}] failed at {1}:{2}\n\tError : {3}", BK_STRINGIFY(check), __FILE__, __LINE__, msg); BK_DEBUGBREAK(); }
#define BK_ASSERT(check) if(!(check)) { BK_ERROR("Assertion [{0}] failed at {1}:{2}", BK_STRINGIFY(check), __FILE__, __LINE__); BK_DEBUGBREAK(); }
#else
#define BK_CORE_VAMSG_ASSERT(check, msg, ...)
#define BK_CORE_MSG_ASSERT(check, msg)
#define BK_CORE_ASSERT(check)
#define BK_VAMSG_ASSERT(check, msg, ...)
#define BK_MSG_ASSERT(check, msg)
#define BK_ASSERT(check)
#endif

@ -1,25 +0,0 @@
#pragma once
#include "log.h"
#define BK_STRINGIFY(x) #x
#define BIT_SHIFT(x) (1 << x)
#define BK_BIND_EVENT_FN(fn) [this](Event& e) { fn(e); }
#define BK_BIND_DISPACHER_FN(event, fn) [this](event& e) -> bool{ return fn(e); }
#ifdef BK_DEBUG
#if defined(BK_PLATFORM_WINDOWS)
#define BK_DEBUGBREAK() __debugbreak()
#elif defined(BK_PLATFORM_LINUX)
#include <signal.h>
#define BK_DEBUGBREAK() raise(SIGTRAP)
#else
#error "Plaform doesn't support debug yet"
#endif
#define BK_ENABLE_ASSERT
#else
#define BK_DEBUGBREAK()
#endif

@ -1,23 +0,0 @@
#include <bkpch.h>
#include "log.h"
#include "application.h"
/*! \file entry.cpp
This file contains the entry point of the program.
*/
/*! \fn std::unique_ptr<Bk::Application> Bk::create_app()
External function implemented client side.
*/
extern std::unique_ptr<Bk::Application> Bk::create_app();
/*! \fn int main(int argc, char** argv)
Entry of the program.
*/
int main(int argc, char** argv) {
Bk::Log::init();
BK_CORE_INFO("Bienvenue dans la sandbox {0} version {1}", "bakara", 1);
std::unique_ptr<Bk::Application> app = Bk::create_app();
app->run();
return 0;
}

@ -1,20 +0,0 @@
#pragma once
#include <bkpch.h>
#include <bakara/events/events.h>
namespace Bk {
class Layer
{
public:
Layer(const std::string& name = "Layer");
virtual ~Layer() {}
virtual void on_attach() {}
virtual void on_detach() {}
virtual void on_event(Event& e) {}
virtual void on_update() {}
const std::string to_string() const { return name; }
protected:
std::string name;
};
}

@ -1,50 +0,0 @@
#include "layer_stack.h"
namespace Bk {
LayerStack::~LayerStack()
{
std::for_each(p_layers.begin(), p_layers.end(), [](Layer* layer)
{
layer->on_detach();
delete layer;
});
p_layers.clear();
}
void LayerStack::push_overlay(Layer* layer)
{
layer->on_attach();
p_layers.emplace_back(layer);
}
std::unique_ptr<Layer> LayerStack::pop_overlay()
{
if(auto layer = p_layers.back())
{
p_layers.pop_back();
return std::make_unique<Layer>(*layer);
}
return nullptr;
}
void LayerStack::push_layer(Layer* layer)
{
layer->on_attach();
p_layers.emplace_front(layer);
}
std::unique_ptr<Layer> LayerStack::pop_layer()
{
if(auto layer = p_layers.front())
{
p_layers.pop_front();
return std::make_unique<Layer>(*layer);
}
return nullptr;
}
void LayerStack::clear()
{
p_layers.clear();
}
}

@ -1,29 +0,0 @@
#pragma once
#include <bkpch.h>
#include "layer.h"
namespace Bk {
class LayerStack
{
public:
LayerStack() = default;
~LayerStack();
void push_overlay(Layer* layer);
std::unique_ptr<Layer> pop_overlay();
void push_layer(Layer* layer);
std::unique_ptr<Layer> pop_layer();
void clear();
std::deque<Layer*>::iterator begin() { return p_layers.begin(); }
std::deque<Layer*>::iterator end() { return p_layers.end(); }
std::deque<Layer*>::reverse_iterator rbegin() { return p_layers.rbegin(); }
std::deque<Layer*>::reverse_iterator rend() { return p_layers.rend(); }
private:
std::deque<Layer*> p_layers;
uint p_layer_index = 0;
};
}

@ -1,28 +0,0 @@
#include "log.h"
namespace Bk {
std::shared_ptr<spdlog::logger> Log::p_core_logger;
std::shared_ptr<spdlog::logger> Log::p_app_logger;
void Log::init()
{
std::vector<spdlog::sink_ptr> log_sinks;
log_sinks.emplace_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
log_sinks.emplace_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("bakara.log", true));
log_sinks[0]->set_pattern("%^[%T] %n: %v%$");
log_sinks[1]->set_pattern("[%T] [%l] %n: %v");
p_core_logger = std::make_shared<spdlog::logger>("BAKARA", begin(log_sinks), end(log_sinks));
spdlog::register_logger(p_core_logger);
p_core_logger->set_level(spdlog::level::trace);
p_core_logger->flush_on(spdlog::level::trace);
p_app_logger = std::make_shared<spdlog::logger>("APP", begin(log_sinks), end(log_sinks));
spdlog::register_logger(p_app_logger);
p_app_logger->set_level(spdlog::level::trace);
p_app_logger->flush_on(spdlog::level::trace);
}
}

@ -1,47 +0,0 @@
#pragma once
#include <bkpch.h>
#include <spdlog/spdlog.h>
#include <spdlog/fmt/ostr.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
namespace Bk {
class Log
{
public:
static void init();
static std::shared_ptr<spdlog::logger>& get_core_logger() { return p_core_logger; }
static std::shared_ptr<spdlog::logger>& get_app_logger() { return p_app_logger; }
private:
static std::shared_ptr<spdlog::logger> p_core_logger;
static std::shared_ptr<spdlog::logger> p_app_logger;
};
#ifdef BK_DEBUG
#define BK_CORE_TRACE(...) ::Bk::Log::get_core_logger()->trace(__VA_ARGS__)
#define BK_CORE_INFO(...) ::Bk::Log::get_core_logger()->info(__VA_ARGS__)
#define BK_CORE_WARN(...) ::Bk::Log::get_core_logger()->warn(__VA_ARGS__)
#define BK_CORE_ERROR(...) ::Bk::Log::get_core_logger()->error(__VA_ARGS__)
#define BK_CORE_CRITICAL(...) ::Bk::Log::get_core_logger()->critical(__VA_ARGS__)
#define BK_TRACE(...) ::Bk::Log::get_app_logger()->trace(__VA_ARGS__)
#define BK_INFO(...) ::Bk::Log::get_app_logger()->info(__VA_ARGS__)
#define BK_WARN(...) ::Bk::Log::get_app_logger()->warn(__VA_ARGS__)
#define BK_ERROR(...) ::Bk::Log::get_app_logger()->error(__VA_ARGS__)
#define BK_CRITICAL(...) ::Bk::Log::get_app_logger()->critical(__VA_ARGS__)
#else
#define BK_CORE_TRACE(...)
#define BK_CORE_INFO(...)
#define BK_CORE_WARN(...)
#define BK_CORE_ERROR(...)
#define BK_CORE_CRITICAL(...)
#define BK_TRACE(...)
#define BK_INFO(...)
#define BK_WARN(...)
#define BK_ERROR(...)
#define BK_CRITICAL(...)
#endif
}

@ -1,32 +0,0 @@
#include "imgui_layer.h"
namespace Bk {
void ImguiLayer::on_attach()
{
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
Application& app = Application::get();
GLFWwindow* window = static_cast<GLFWwindow*>(app.get_window()->get_native_window());
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 410");
}
void ImguiLayer::on_detach()
{
}
void ImguiLayer::on_event(Bk::Event& e)
{
}
void ImguiLayer::on_update()
{
}
}

@ -1,23 +0,0 @@
#pragma once
#include <imgui.h>
#include <backends/imgui_impl_opengl3.h>
#include <backends/imgui_impl_glfw.h>
#include <bakara/core/application.h>
#include <bakara/core/layer.h>
namespace Bk {
class ImguiLayer : public Layer
{
public:
ImguiLayer()
: Layer("Imgui") {}
~ImguiLayer() = default;
void on_attach() override;
void on_detach() override;
void on_event(Bk::Event& e) override;
void on_update() override;
};
}

@ -1,8 +0,0 @@
#pragma once
/*! \file mathpch.h
Precompiled headers communly used in math functionnalitys.
*/
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

@ -1,47 +0,0 @@
#pragma once
#include <bkpch.h>
#include <bakara/io/window.h>
#include <bakara/events/events.h>
#include <mutex>
#include <GLFW/glfw3.h>
namespace Bk::Plaform {
class WinGLFW : public Window
{
public:
WinGLFW(const WindowProps& props);
virtual ~WinGLFW();
inline uint get_width() const override { return p_data.width; }
inline uint get_height() const override { return p_data.height; }
void on_update() override;
void set_event_callback(const EventCallback callback) override;
void set_vsync(bool enable) override;
bool is_vsync() const override;
void close() override;
void open() override;
void* get_native_window() override { return p_window; }
private:
GLFWwindow* p_window;
bool p_shutdown;
struct WindowData
{
std::string title;
uint width;
uint height;
bool vsync;
EventCallback callback;
};
WindowData p_data;
void init_event_callbacks();
void init();
void shutdown();
};
}

@ -1,65 +0,0 @@
#pragma once
/*! \file string_fmt.h
This file provides functions to do string formatting.
*/
#include <bkpch.h>
#include <type_traits>
#include <cctype>
namespace Bk::Tools {
inline void format_impl(std::stringstream& ss, const char* format) {
while (*format) {
if (*format == '%' && *++format != '%') // %% == % (not a format directive)
throw std::invalid_argument("not enough arguments !\n");
ss << *format++;
}
}
template <typename Arg, typename... Args>
void format_impl(std::stringstream& ss, const char* format, Arg arg, Args... args) {
while (*format) {
if (*format == '%' && *++format != '%') {
auto current_format_qualifier = *format;
switch(current_format_qualifier) {
case 'd' :
if (!std::is_integral<Arg>()) throw std::invalid_argument("%d introduces integral argument");
break;
case 'f' :
if (!std::is_floating_point<Arg>()) throw std::invalid_argument("%f introduces floating point argument");
break;
case 'b' :
if(arg) ss << "true";
else ss << "false";
return format_impl(ss, ++format, args...);
case 's' :
break;
// etc.
default:
throw std::invalid_argument("Not a standard format");
break;
}
// it's true you'd have to handle many more format qualifiers, but on a safer basis
ss << arg; // arg type is deduced
return format_impl(ss, ++format, args...); // one arg less
}
ss << *format++;
} // the format string is exhausted and we still have args : throw
throw std::invalid_argument("Too many arguments\n");
}
/*! \fn std::string Bk::Tools::format(const char* fmt, Args... args)
Formats a string, printf like. Accepts integers, floating point numbers, strings, booléen.
@param fmt : string to format
@param args : variable arguments to put in the string
@return String formatted
*/
template <typename... Args>
inline std::string format(const char* fmt, Args... args) {
std::stringstream ss;
format_impl(ss, fmt, args...);
return ss.str();
}
}

@ -1,21 +0,0 @@
#pragma once
/*! \file bkpch.h
Precompiled headers communly used in bakara.
*/
#include <iostream>
#include <ostream>
#include <utility>
#include <memory>
#include <functional>
#include <string>
#include <sstream>
#include <array>
#include <vector>
#include <deque>
#include <exception>
#include <bakara/core/log.h>
#include <bakara/core/assert.h>
#include <bakara/math/type.h>

@ -1,311 +0,0 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
# define KHRONOS_STATIC 1
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(KHRONOS_STATIC)
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
* header compatible with static linking. */
# define KHRONOS_APICALL
#elif defined(_WIN32)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
/*
* To support platform where unsigned long cannot be used interchangeably with
* inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t.
* Ideally, we could just use (u)intptr_t everywhere, but this could result in
* ABI breakage if khronos_uintptr_t is changed from unsigned long to
* unsigned long long or similar (this results in different C++ name mangling).
* To avoid changes for existing platforms, we restrict usage of intptr_t to
* platforms where the size of a pointer is larger than the size of long.
*/
#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__)
#if __SIZEOF_POINTER__ > __SIZEOF_LONG__
#define KHRONOS_USE_INTPTR_T
#endif
#endif
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef KHRONOS_USE_INTPTR_T
typedef intptr_t khronos_intptr_t;
typedef uintptr_t khronos_uintptr_t;
#elif defined(_WIN64)
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
#endif
#if defined(_WIN64)
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1 +0,0 @@
Subproject commit 8e6c8d7effc54f8aecd30eda17069588298f4ada

1
bakara/vendor/glm vendored

@ -1 +0,0 @@
Subproject commit b06b775c1c80af51a1183c0e167f9de3b2351a79

@ -1 +0,0 @@
Subproject commit 96839b445e32e46d87a44fd43a9cdd60c806f7e1

@ -1,157 +0,0 @@
project "GLFW"
location "./glfw"
kind "StaticLib"
language "C"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
includedirs { "%{prj.location}/include" }
files
{
"%{prj.location}/src/internal.h",
"%{prj.location}/src/platform.h",
"%{prj.location}/src/mappings.h",
"%{prj.location}/src/context.c",
"%{prj.location}/src/init.c",
"%{prj.location}/src/input.c",
"%{prj.location}/src/monitor.c",
"%{prj.location}/src/window.c",
"%{prj.location}/src/platform.c",
"%{prj.location}/src/vulkan.c",
"%{prj.location}/src/null_init.c",
"%{prj.location}/src/null_monitor.c",
"%{prj.location}/src/null_window.c",
"%{prj.location}/src/null_joystick.c",
"%{prj.location}/src/glfw_config.h",
"%{prj.location}/include/GLFW/glfw3native.h",
"%{prj.location}/include/GLFW/glfw3.h",
"include/GLFW/glfw3.h",
"include/GLFW/glfw3native.h",
}
filter "system:linux"
pic "On"
systemversion "latest"
files
{
"%{prj.location}/src/x11_init.c",
"%{prj.location}/src/x11_monitor.c",
"%{prj.location}/src/x11_window.c",
"%{prj.location}/src/xkb_unicode.c",
"%{prj.location}/src/posix_time.c",
"%{prj.location}/src/posix_module.c",
"%{prj.location}/src/posix_poll.c",
"%{prj.location}/src/posix_thread.c",
"%{prj.location}/src/glx_context.c",
"%{prj.location}/src/egl_context.c",
"%{prj.location}/src/osmesa_context.c",
"%{prj.location}/src/linux_joystick.c"
}
defines
{
"_GLFW_X11"
}
filter "system:windows"
systemversion "latest"
staticruntime "On"
files
{
"%{prj.location}/src/win32_init.c",
"%{prj.location}/src/win32_joystick.c",
"%{prj.location}/src/win32_monitor.c",
"%{prj.location}/src/win32_time.c",
"%{prj.location}/src/win32_module.c",
"%{prj.location}/src/win32_thread.c",
"%{prj.location}/src/win32_window.c",
"%{prj.location}/src/wgl_context.c",
"%{prj.location}/src/egl_context.c",
"%{prj.location}/src/osmesa_context.c"
}
defines
{
"_GLFW_WIN32",
"_CRT_SECURE_NO_WARNINGS"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
project "GLAD"
location "./glad"
kind "StaticLib"
language "C"
systemversion "latest"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
includedirs { "%{prj.location}/include" }
buildoptions { "-fPIC" }
files
{
"%{prj.location}/src/glad.c",
"%{prj.location}/include/KHR/khrplatform.h",
"%{prj.location}/include/glad.h"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
project "ImGui"
location "./imgui"
kind "StaticLib"
language "C++"
systemversion "latest"
cppdialect "C++17"
staticruntime "On"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.location}/imconfig.h",
"%{prj.location}/imgui.h",
"%{prj.location}/imgui.cpp",
"%{prj.location}/imgui_draw.cpp",
"%{prj.location}/imgui_internal.h",
"%{prj.location}/imgui_widgets.cpp",
"%{prj.location}/imstb_rectpack.h",
"%{prj.location}/imstb_textedit.h",
"%{prj.location}/imstb_truetype.h",
"%{prj.location}/imgui_demo.cpp",
"%{prj.location}/imgui_tables.cpp",
}
filter "system:linux"
pic "On"
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"

@ -1 +0,0 @@
Subproject commit 696db97f672e9082e50e50af315d0f4234c82397

@ -1,57 +0,0 @@
clear
echo ==================
echo [BUILDING PROJECT]
echo ==================
echo number of lines :
find ./bakara/src -name *.cpp -or -name *.h -exec cat {} \; | wc -l
if [ -z ${clear} ]; then
clear=0
else
clear=1
fi
if [ -z ${exec} ]; then
exec=0
else
exec=1
fi
if [ 1 -eq ${clear} ]; then
echo Clearing bin/bin-int dirs
rm -rf bin bin-int
else
echo Caching bin/bin-int dirs
fi
echo
premake5 gmake
echo
make $1
if [ $? -eq 0 ]; then
echo Compilation Success
echo ================
echo [FINISHED BUILD]
echo ================
if [ 1 -eq ${exec} ]; then
config=$1
if [ -z "$config" ]; then
config="config=debug"
fi
if [ "config=debug" == "$config" ]; then
echo
echo ==============
echo [STARTING APP]
echo ==============
echo Config: Debug
bin/linux-x86_64-Debug/sandbox/sandbox
elif [ "config=release" == "$config" ]; then
echo [STARTING APP]
echo [Config: Release]
bin/linux-x86_64-Release/sandbox/sandbox
else
echo [Aborted Launch]
echo [Config Unknown]
fi
fi
else
echo Error will compiling
fi

@ -0,0 +1,11 @@
IncludeDirs["bakara"] = "%{wks.location}/vendor/bakara/src"
IncludeDirs["glm"] = "%{wks.location}/vendor/glm"
IncludeDirs["stb"] = "%{wks.location}/vendor/stb"
group "Bakara"
include "vendor/bakara"
include "vendor/glfw"
include "vendor/glad"
include "vendor/imgui"
group ""

@ -0,0 +1,32 @@
#include <memory>
#include <utility>
#include <string>
#include <bakara.h>
class TestLayer : public Bk::Layer
{
public:
TestLayer()
: Layer("Test") {}
void ImguiRender() override
{
static bool show = true;
ImGui::ShowDemoWindow(&show);
}
};
class Sandbox : public Bk::Application
{
public:
Sandbox()
{
PushLayer(new TestLayer());
}
};
std::unique_ptr<Bk::Application> Bk::CreateApp() {
return std::unique_ptr<Bk::Application>(new Sandbox());
}

@ -3,10 +3,6 @@
#include <string>
#include <bakara.h>
#include <bakara/events/events.h>
//USE THE FUCKING NAMESPACE OR BREAK
class TestLayer : public Bk::Layer
{
public:
@ -23,12 +19,12 @@ class TestLayer : public Bk::Layer
BK_INFO("Layer {} detached", name);
}
void on_event(Bk::Event& e) override
void OnEvent(Bk::Event& e) override
{
BK_INFO("Layer {} event", name);
}
void on_update() override
void OnUpdate() override
{
BK_INFO("Layer {} updated", name);
}
@ -39,21 +35,10 @@ class Sandbox : public Bk::Application
public:
Sandbox()
{
push_layer(new TestLayer());
push_layer(new TestLayer());
std::unique_ptr<Bk::Layer> layer = pop_overlay();
BK_INFO("Layer retirer et récupérer {0}", layer->to_string());
}
~Sandbox()
{
PushLayer(new TestLayer());
}
};
std::unique_ptr<Bk::Application> Bk::create_app() {
std::unique_ptr<Bk::Application> Bk::CreateApp() {
return std::unique_ptr<Bk::Application>(new Sandbox());
}

@ -1,32 +1,2 @@
\mainpage Bakara Manual
## Build
### Windows
On windows, write commands :
```batch
git clone https://github.com/anulax/bakara
git submodule init
git submodule update
.\vendor\premake5 vs2022
dotnet build
dotnet run
```
Or use visual studio 2022 to build your project.
### Linux
On linux (if you don't have premake5, install it with your distro's packet manager). You have two env variable to change build proccess :
| Name | Value |
| ----------- | ----------- |
| autoexec | 0/1 |
| clearbin | 0/1 |
Then write commands :
```bash
git clone https://github.com/anulax/bakara
git submodule init
git submodule update
(export clearbin=1 autoexec=1)
./build.sh config=release
```

@ -0,0 +1,45 @@
{
"name": "Bakara",
"author": "anulax1225",
"git": "https://github.com/anulax1225/bakara",
"links":
[
"bakara"
],
"includes":
[
"bakara",
"glm"
],
"packages":
[
{
"author": "anulax1225",
"name": "bakatools"
},
{
"author": "anulax1225",
"name": "glm"
},
{
"author": "anulax1225",
"name": "glfw"
},
{
"author": "anulax1225",
"name": "glad"
},
{
"author": "anulax1225",
"name": "imgui-docking"
},
{
"author": "anulax1225",
"name": "imgui"
},
{
"author": "anulax1225",
"name": "stb"
}
]
}

@ -1,39 +1,97 @@
workspace "Bakara"
architecture "x64"
configurations { "Debug", "Release" }
startproject "sandbox"
project "bakara"
kind "StaticLib"
language "C++"
cppdialect "C++20"
flags
{
"MultiProcessorCompile"
}
targetdir("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
linkgroups "On"
files
{
"%{wks.location}/vendor/glm/glm/**.hpp",
"%{wks.location}/vendor/glm/glm/**.inl",
"%{wks.location}/vendor/stb/stb_image.h",
"%{wks.location}/vendor/stb/stb_image.cpp",
"src/bakara/**.h",
"src/bakara/**.cpp",
"src/platforms/**.h",
"src/platforms/**.cpp",
}
outputdir = "%{cfg.system}-%{cfg.architecture}-%{cfg.buildcfg}"
defines
{
"_CRT_SECURE_NO_WARNINGS",
"GLFW_INCLUDE_NONE",
}
IncludeDirs = {}
IncludeDirs["bakara"] = "%{wks.location}/bakara/src"
IncludeDirs["vendor"] = "%{wks.location}/bakara/vendor"
IncludeDirs["spdlog"] = "%{wks.location}/bakara/vendor/spdloglib/include"
IncludeDirs["glm"] = "%{wks.location}/bakara/vendor/glm"
IncludeDirs["glfw"] = "%{wks.location}/bakara/vendor/glfw/include"
IncludeDirs["glad"] = "%{wks.location}/bakara/vendor/glad/include"
IncludeDirs["imgui"] = "%{wks.location}/bakara/vendor/imgui"
includedirs
{
"%{IncludeDirs.bakara}",
"%{IncludeDirs.glm}",
"%{IncludeDirs.spdlog}",
"%{IncludeDirs.glad}",
"%{IncludeDirs.glfw}",
"%{IncludeDirs.imgui}",
"%{IncludeDirs.bakatools}",
"%{IncludeDirs.stb}"
}
links
{
"bakatools",
"GLFW",
"GLAD",
"ImGui"
}
group "Dependencies"
include "bakara/vendor"
group ""
filter "configurations:Debug"
--buildoptions { "-Wall", "-Wextra" }
defines
{
"BK_DEBUG",
"DEBUG"
}
runtime "Debug"
symbols "on"
group "Core"
include "bakara"
group ""
group "App"
include "sandbox"
group ""
filter "configurations:Release"
defines
{
"BK_RELEASE",
"NDEBUG"
}
runtime "Release"
optimize "on"
filter "system:windows"
buildoptions "/MT"
staticruntime "on"
defines
{
"BK_PLATFORM_WINDOWS"
}
links
{
"opengl32.lib"
}
filter "system:linux"
staticruntime "on"
buildoptions { "-fPIC" }
files
{
"%{wks.location}/vendor/glm/glm/**.cpp"
}
defines
{
"BK_PLATFORM_LINUX"
}
links
{
"GL"
}

@ -1,59 +0,0 @@
project "sandbox"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
systemversion "latest"
targetdir("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"src/**.h",
"src/**.cpp"
}
includedirs
{
"%{IncludeDirs.bakara}",
"%{IncludeDirs.spdlog}",
"%{IncludeDirs.glm}"
}
links
{
"bakara"
}
filter "configurations:Debug"
defines
{
"BK_DEBUG",
"DEBUG"
}
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines
{
"BK_RELEASE",
"NDEBUG"
}
runtime "Release"
optimize "on"
filter "system:windows"
staticruntime "on"
defines
{
"BK_PLATFORM_WINDOWS"
}
filter "system:linux"
staticruntime "on"
defines
{
"BK_PLATFORM_LINUX"
}

@ -0,0 +1,37 @@
#pragma once
/*! \file bakara.h
Precompiled headers for external pragrams.
*/
/*! \namespace Bk
Global namespace doc
*/
namespace Bk {}
/*! \namespace Bk::Plaform
Plaform namespace doc
*/
namespace Bk::Plaform {}
#include <bakara/math/types.h>
#include <bakara/io/io_codes.h>
#include <bakara/io/keyboard.h>
#include <bakara/io/mouse.h>
#include <bakara/events/events.h>
#include <bakara/core/application.h>
#include <bakara/core/layer.h>
#include <bakara/renderer/cameras/ortho_camera.h>
#include <bakara/renderer/cameras/ortho_camera_controller.h>
#include <bakara/renderer/render_command.h>
#include <bakara/renderer/renderer.h>
#include <bakara/renderer/renderer2D.h>
#include <bakara/renderer/texture.h>
#include <bakara/renderer/buffer.h>
#include <bakara/renderer/buffer_layout.h>
#include <bakara/renderer/shader.h>
#include <bakara/renderer/vertex_array.h>

@ -0,0 +1,73 @@
#include "application.h"
#include "bakara/core/window.h"
#include "bakara/events/window_event.h"
#include "bakara/renderer/renderer.h"
#include "bakatools/logging/assert.h"
#include "bakara/events/dispacher.h"
namespace Bk {
Application* Application::p_instance = nullptr;
Application::Application(std::string title, u32 width, u32 height)
{
BK_CORE_MSG_ASSERT(p_instance == nullptr, "Application already exists, can not create two application.")
Application::p_instance = this;
h_window = std::unique_ptr<Window>(Window::CreateWindow(WindowProps(title, width, height)));
h_window->SetEventCallback(BK_BIND_EVENT_FN(OnEvent));
Renderer::Init();
imgui_layer = new ImguiLayer();
PushOverlay(imgui_layer);
}
Application::~Application() { }
void Application::OnEvent(Event& e)
{
EventDispatcher dispatcher(e);
if (!dispatcher.dispatch<WindowCloseEvent>(BK_BIND_DISPACHER_FN(WindowCloseEvent, OnWindowClose)))
{
dispatcher.dispatch<WindowResizeEvent>(BK_BIND_DISPACHER_FN(WindowResizeEvent, OnWindowResize));
for(auto it = p_layer_stack.ReverseBegin(); it != p_layer_stack.ReverseEnd(); it++)
{
(*it)->OnEvent(e);
}
}
}
void Application::Close()
{
p_running = false;
}
bool Application::OnWindowResize(WindowResizeEvent& e)
{
isMinimized = !e.GetWidth() && !e.GetHeight();
Renderer::ResizeFrame(e.GetWidth(), e.GetHeight());
return false;
}
bool Application::OnWindowClose(WindowCloseEvent& e)
{
Close();
return true;
}
void Application::Run()
{
while (p_running)
{
if (!isMinimized)
for (Layer* layer : p_layer_stack)
layer->OnUpdate(h_window->GetTime());
imgui_layer->Begin();
for (Layer* layer : p_layer_stack)
layer->ImguiRender();
imgui_layer->End();
h_window->OnUpdate();
}
}
}

@ -4,10 +4,11 @@
This file contains the main app abstraction.
*/
#include <bkpch.h>
#include <bakara/io/window.h>
#include <bakara/events/events.h>
#include <bakara/core/layer_stack.h>
#include "bakara/events/window_event.h"
#include "bakatools/container/types.h"
#include "bakara/core/window.h"
#include "bakara/core/layer_stack.h"
#include "bakara/imgui/imgui_layer.h"
namespace Bk {
/*! \class Bk::Application
@ -20,71 +21,76 @@ namespace Bk {
/*! \fn Bk::Application
Initializes the main window and binds the event callback
*/
Application();
Application(std::string name = "BakaraEngine", u32 width = 1000, u32 height = 800);
/*! \fn Bk::Application::~Application
Virtual destructor enables subclasses to cleanup on termination
*/
virtual ~Application();
/*! \fn Bk::Application::on_event
/*! \fn Bk::Application::OnEvent
Function bound to the window to get all event from it
@param e : Event to be processed
*/
void on_event(Event& e);
void OnEvent(Event& e);
/*! \fn Bk::Application::on_window_close
/*! \fn Bk::Application::OnWindowClose
Handler of Bk::WindowCloseEvent and will be bind to a event dispacher
@param e : event to handled
*/
virtual bool on_window_close(WindowCloseEvent& e);
/*! \fn Bk::Application::on_window_resize
virtual bool OnWindowClose(WindowCloseEvent& e);
/*! \fn Bk::Application::OnWindowResize
Handler of Bk::WindowResizeEvent and will be bind to a event dispacher
@param e : event to handled
*/
virtual bool on_window_resize(WindowResizeEvent& e);
virtual bool OnWindowResize(WindowResizeEvent& e);
/*! \fn Bk::Application::push_overlay
/*! \fn Bk::Application::PushOverlay
Push's the layer on top of the layer stack
@param layer : Layer pointer to push
*/
inline void push_overlay(Layer* layer) { p_layer_stack.push_overlay(layer); }
/*! \fn Bk::Application::pop_overlay
inline void PushOverlay(Layer* layer) { p_layer_stack.PushOverlay(layer); }
/*! \fn Bk::Application::PopOverlay
Pop's the layer on top of the layer stack
@return a unique ptr to the layer ressource
*/
inline std::unique_ptr<Layer> pop_overlay() { return p_layer_stack.pop_overlay(); }
/*! \fn Bk::Application::push_overlay
inline void PopOverlay(Layer* layer) { p_layer_stack.PopOverlay(layer); }
/*! \fn Bk::Application::PushOverlay
Push's the layer at the bottom of the layer stack
@param layer : Layer pointer to push
*/
inline void push_layer(Layer* layer) { p_layer_stack.push_layer(layer); }
/*! \fn Bk::Application::push_overlay
inline void PushLayer(Layer* layer) { p_layer_stack.PushLayer(layer); }
/*! \fn Bk::Application::PushOverlay
Pop's the layer at the bottom of the layer stack
@return a unique ptr to the layer ressource
*/
inline std::unique_ptr<Layer> pop_layer() { return p_layer_stack.pop_layer(); }
inline void PopLayer(Layer* layer) { p_layer_stack.PopLayer(layer); }
/*! \fn Bk::Application::run
Starts the application and the update loop.
*/
void run();
void Run();
std::shared_ptr<Window> get_window() { return std::shared_ptr<Window>(h_window); }
Window& GetWindow() { return *h_window; }
static Application& get() { return *p_instance; }
static Application& Get() { return *p_instance; }
protected:
std::shared_ptr<Window> h_window; //!< Pointer to the main window
std::unique_ptr<Window> h_window; //!< Pointer to the main window
ImguiLayer* imgui_layer;
/*! \fn Bk::Application::Close
Stops the application and the update loop without creating an event.
*/
void Close();
private:
LayerStack p_layer_stack; //!< Layer stack of the application
bool p_running; //!< Flag that indicates if the update loop should stop or not
bool p_running = true; //!< Flag that indicates if the update loop should stop or not
bool isMinimized = false;
static Application* p_instance;
};
/*! \fn std::unique_ptr<Application> Bk::create_app()
/*! \fn std::unique_ptr<Application> Bk::CreateApp()
Is used to retrive the user app class instance, made from inheritance.
Must be defined in the user program
@return User defined application
*/
std::unique_ptr<Application> create_app();
Application* CreateApp(int argc, char** argv);
}

@ -0,0 +1,17 @@
#pragma once
namespace Bk
{
class DeltaTime
{
public:
DeltaTime(float time = 0.0f) : time(time)
{}
operator float() { return time; }
float GetSeconds() { return time; }
float GetMilliseconds() { return time *1000.0f; }
private:
float time;
};
}

@ -0,0 +1,21 @@
#include "application.h"
/*! \file entry.cpp
This file contains the entry point of the program.
*/
/*! \fn std::unique_ptr<Bk::Application> Bk::CreateApp()
External function implemented client side.
*/
extern Bk::Application* Bk::CreateApp(int argc, char** argv);
/*! \fn int main(int argc, char** argv)
Entry of the program.
*/
int main(int argc, char** argv) {
Bk::Log::Init("Bakara");
Bk::Application* app = Bk::CreateApp(argc, argv);
app->Run();
delete app;
return 0;
}

@ -0,0 +1,23 @@
#pragma once
#include "bakara/core/deltatime.h"
#include "bakara/events/event.h"
#include <string>
namespace Bk {
class Layer
{
public:
Layer(const std::string& name = "Layer");
~Layer() {}
virtual void OnAttach() {}
virtual void OnDetach() {}
virtual void OnEvent(Event& e) {}
virtual void OnUpdate(DeltaTime dt) {}
virtual void ImguiRender() {}
const std::string ToString() const { return name; }
protected:
std::string name;
};
}

@ -0,0 +1,50 @@
#include "layer_stack.h"
namespace Bk {
LayerStack::~LayerStack() { clear(); }
void LayerStack::PushOverlay(Layer* layer)
{
layer->OnAttach();
p_layers.emplace_back(layer);
}
void LayerStack::PopOverlay(Layer* layer)
{
auto it = std::find(p_layers.begin() + p_layer_index, p_layers.end(), layer);
if (it != p_layers.end())
{
layer->OnDetach();
p_layers.erase(it);
}
}
void LayerStack::PushLayer(Layer* layer)
{
layer->OnAttach();
p_layers.emplace(p_layers.begin() + p_layer_index, layer);
p_layer_index++;
}
void LayerStack::PopLayer(Layer* layer)
{
auto it = std::find(p_layers.begin(), p_layers.begin() + p_layer_index, layer);
if (it != p_layers.begin() + p_layer_index)
{
layer->OnDetach();
p_layers.erase(it);
p_layer_index--;
}
}
void LayerStack::clear()
{
std::for_each(p_layers.begin(), p_layers.end(), [](Layer* layer)
{
layer->OnDetach();
delete layer;
});
p_layers.clear();
p_layer_index = 0;
}
}

@ -0,0 +1,31 @@
#pragma once
#include "layer.h"
#include <vector>
namespace Bk {
class LayerStack
{
public:
LayerStack() = default;
~LayerStack();
void PushOverlay(Layer* layer);
void PopOverlay(Layer* layer);
void PushLayer(Layer* layer);
void PopLayer(Layer* layer);
void clear();
std::vector<Layer*>::iterator begin() { return p_layers.begin(); }
std::vector<Layer*>::iterator end() { return p_layers.end(); }
std::vector<Layer*>::iterator Begin() { return p_layers.begin(); }
std::vector<Layer*>::iterator End() { return p_layers.end(); }
std::vector<Layer*>::reverse_iterator ReverseBegin() { return p_layers.rbegin(); }
std::vector<Layer*>::reverse_iterator ReverseEnd() { return p_layers.rend(); }
private:
std::vector<Layer*> p_layers;
uint p_layer_index = 0;
};
}

@ -5,8 +5,11 @@ This file contiens all the interfaces to create a window.
Implementation possible with GLFW, Win32, etc.
*/
#include <bkpch.h>
#include <bakara/events/event.h>
#include "bakara/core/deltatime.h"
#include "bakara/events/event.h"
#include "bakatools/container/types.h"
#include <functional>
#include <string>
namespace Bk {
@ -20,15 +23,21 @@ namespace Bk {
uint height; //!< Height of the window
/*! \fn Bk::WindowProps::WindowProps
Default window is initialized with a width of 1000 and a height 800
Default window is Initialized with a width of 1000 and a height 800
@param title : Title of the window
@param width : Width of the window
@param height : Height of the window
*/
WindowProps(std::string title = "Bakara engine", uint width = 1000, uint height = 800)
WindowProps(std::string title, u32 width, u32 height)
: title(title), width(width), height(height) {}
};
/*! \typedef Bk::Window::EventCallback
The EventCallback is a function pointer that takes a Event as parameter
and that reponses to them.
*/
using EventCallback = std::function<void(Event& e)>;
/*! \class Bk::Window
Window is an interface to abstract witch window api is used. This enable compilation with multiple api,
so that it's possible to use the native api of the platform or to implement a graphics api's with more ease.
@ -36,70 +45,55 @@ namespace Bk {
class Window
{
public:
/*! \typedef Bk::Window::EventCallback
The EventCallback is a function pointer that takes a Event as parameter
and that reponses to them.
*/
using EventCallback = std::function<void(Event& e)>;
/*! \fn Bk::Window::~Window
Virtual destructor enables subclasses to cleanup on termination.
*/
virtual ~Window() {}
/*! \fn Bk::Window::get_width
/*! \fn Bk::Window::GetWidth
@return The width of the window
*/
virtual uint get_width() const = 0;
/*! \fn Bk::Window::get_height
virtual uint GetWidth() const = 0;
/*! \fn Bk::Window::GetHeight
@return The height of the window
*/
virtual uint get_height() const = 0;
virtual uint GetHeight() const = 0;
/*! \fn Bk::Window::on_update
/*! \fn Bk::Window::OnUpdate
Updates the frame of the window
*/
virtual void on_update() = 0;
/*! \fn Bk::Window::set_event_callback
virtual void OnUpdate() = 0;
/*! \fn Bk::Window::SetEventCallback
Sets the function pointer for events of the window
@param callback : function called when a new event occures
*/
virtual void set_event_callback(const EventCallback callback) = 0;
virtual void SetEventCallback(const EventCallback callback) = 0;
/*! \fn Bk::Window::set_vsync
/*! \fn Bk::Window::SetVsync
Sets the window buffer swap interval. Is enabled by default.
If set to false the frame rate should be more constant, but more slow.
*/
virtual void set_vsync(bool enable) = 0;
/*! \fn Bk::Window::is_vsync
virtual void SetVsync(bool enable) = 0;
/*! \fn Bk::Window::IsVsync
Indicates if window is vsync
@return Vsync flag
*/
virtual bool is_vsync() const = 0;
virtual bool IsVsync() const = 0;
/*! \fn Bk::Window::close
/*! \fn Bk::Window::Close
Closes the window
*/
virtual void close() = 0;
/*! \fn Bk::Window::open
Opens and initializes the window
*/
virtual void open() = 0;
/*! \fn Bk::Window::is_open
Indicates if the window is opened
@return Open flag
*/
bool is_open() { return h_is_open; }
virtual void Close() = 0;
virtual void* GetNativeWindow() = 0;
virtual void* get_native_window() = 0;
virtual DeltaTime GetTime() = 0;
/*! \fn Bk::Window::create_window()
/*! \fn Bk::Window::CreateWindow()
Static function implemented in the api window class to get a window specifique api.
If no parameter is specified, creates the window with the default settings.
@param props : Window information
*/
static Window* create_window(const WindowProps& props = WindowProps());
protected:
bool h_is_open; //!< indicaste if the window is opened or not
static Window* CreateWindow(const WindowProps& props);
};
}

@ -0,0 +1,28 @@
#pragma once
#include "bakara/events/event.h"
namespace Bk {
class EventDispatcher
{
public:
EventDispatcher(Event& event)
: p_event(event) {}
// F will be deduced by the compiler
template<typename T, typename F>
bool dispatch(const F& func)
{
if (p_event.get_event_type() == T::get_static_type())
{
p_event.handled |= func(static_cast<T&>(p_event));
return true;
}
return false;
}
inline Event& get_event() { return p_event; }
private:
Event& p_event;
};
}

@ -1,8 +1,11 @@
#pragma once
#include <bakara/core/base.h>
#include <bkpch.h>
#include <bakara/tools/string_fmt.h>
#include "bakatools/base.h"
#include "bakatools/string/format.h"
#include <string>
#define BK_BIND_EVENT_FN(fn) [this](Event& e) { fn(e); }
#define BK_BIND_DISPACHER_FN(event, fn) [this](event& e) -> bool{ return fn(e); }
namespace Bk {
enum class EventType
@ -28,11 +31,11 @@ namespace Bk {
enum EventCategory
{
None = 0,
AppCategory = BIT_SHIFT(0),
InputCategory = BIT_SHIFT(1),
KeyboardCategory = BIT_SHIFT(2),
MouseCategory = BIT_SHIFT(3),
MouseButtonCategory = BIT_SHIFT(4)
AppCategory = BK_BIT_SHIFT(0),
InputCategory = BK_BIT_SHIFT(1),
KeyboardCategory = BK_BIT_SHIFT(2),
MouseCategory = BK_BIT_SHIFT(3),
MouseButtonCategory = BK_BIT_SHIFT(4)
};
#define EVENT_CLASS_TYPE(type) static EventType get_static_type() { return EventType::type; }\
@ -42,9 +45,9 @@ namespace Bk {
#define EVENT_CLASS_CATEGORY(category) virtual int get_category_flags() const override { return category; }
#ifdef BK_DEBUG
#define EVENT_STRINGIFY(str, ...) std::string to_string() const override { return Tools::format(str, __VA_ARGS__); }
#define EVENT_STRINGIFY(str, ...) std::string ToString() const override { return Tools::string_format(str, __VA_ARGS__); }
#define GET_EVENT_STRING(event) event.to_string()
#define GET_EVENT_STRING(event) event.ToString()
#else
#define EVENT_STRINGIFY(str, ...)
@ -62,31 +65,8 @@ namespace Bk {
virtual const char* get_name() const = 0;
virtual int get_category_flags() const = 0;
#ifdef BK_DEBUG
virtual std::string to_string() const { return get_name(); }
virtual std::string ToString() const { return get_name(); }
#endif
bool is_in_category(EventCategory category) { return get_category_flags() & category; }
};
class EventDispatcher
{
public:
EventDispatcher(Event& event)
: p_event(event) {}
// F will be deduced by the compiler
template<typename T, typename F>
bool dispatch(const F& func)
{
if (p_event.get_event_type() == T::get_static_type())
{
p_event.handled |= func(static_cast<T&>(p_event));
return true;
}
return false;
}
inline Event& get_event() { return p_event; }
private:
Event& p_event;
};
}

@ -1,35 +1,34 @@
#pragma once
#include <bakara/io/io_codes.h>
#include "bakara/io/key_codes.h"
#include "event.h"
namespace Bk {
class KeyEvent : public Event
{
public:
KeyCode get_key() const { return m_key; }
Code get_key() const { return m_key; }
EVENT_CLASS_CATEGORY(KeyboardCategory | InputCategory)
protected:
KeyEvent(const KeyCode key)
KeyEvent(const Code key)
: m_key(key) {}
KeyCode m_key;
Code m_key;
};
class KeyPressEvent : public KeyEvent
{
public:
KeyPressEvent(KeyCode key, bool is_repeated = false)
: KeyEvent(key), p_is_repeated(is_repeated) {}
KeyPressEvent(Code key, bool IsRepeated = false)
: KeyEvent(key), p_is_repeated(IsRepeated) {}
EVENT_CLASS_TYPE(KeyPress)
EVENT_STRINGIFY("KeyPressEvent: %d repeat : %b", m_key, p_is_repeated)
bool is_repeated() { return p_is_repeated; }
bool IsRepeated() { return p_is_repeated; }
private:
bool p_is_repeated;
@ -38,7 +37,7 @@ namespace Bk {
class KeyReleaseEvent : public KeyEvent
{
public:
KeyReleaseEvent(KeyCode key)
KeyReleaseEvent(Code key)
: KeyEvent(key) {}
EVENT_CLASS_TYPE(KeyRelease)
@ -49,7 +48,7 @@ namespace Bk {
class KeyTypedEvent : public KeyEvent
{
public:
KeyTypedEvent(const KeyCode keycode)
KeyTypedEvent(const Code keycode)
: KeyEvent(keycode) {}
EVENT_CLASS_TYPE(KeyTyped)

@ -1,8 +1,8 @@
#pragma once
#include "bakara/io/mouse_codes.h"
#include "event.h"
#include <bakara/math/type.h>
#include <bakara/io/io_codes.h>
#include "bakara/math/types.h"
namespace Bk
{
@ -12,8 +12,8 @@ namespace Bk
MouseMoveEvent(const float x, const float y)
: p_mouse_x(x), p_mouse_y(y) {}
float get_x() const { return p_mouse_x; }
float get_y() const { return p_mouse_y; }
float GetX() const { return p_mouse_x; }
float GetY() const { return p_mouse_y; }
Vec2 get_pos() const { return Vec2(p_mouse_x, p_mouse_y); }
@ -33,8 +33,8 @@ namespace Bk
MouseScrollEvent(const float x, const float y)
: p_dx(x), p_dy(y) {}
float get_dx() const { return p_dx; }
float get_dy() const { return p_dy; }
float GetDx() const { return p_dx; }
float GetDY() const { return p_dy; }
EVENT_STRINGIFY("MouseScrollEvent : (%f, %f)", p_dx, p_dy)
@ -48,19 +48,19 @@ namespace Bk
class MouseButtonEvent : public Event
{
public:
MouseCode get_btn() { return m_btn; }
Code GetBtn() { return m_btn; }
EVENT_CLASS_CATEGORY(MouseCategory | InputCategory)
protected:
MouseButtonEvent(MouseCode btn)
MouseButtonEvent(Code btn)
: m_btn(btn) {}
MouseCode m_btn;
Code m_btn;
};
class MouseButtonPressEvent : public MouseButtonEvent
{
public:
MouseButtonPressEvent(MouseCode btn)
MouseButtonPressEvent(Code btn)
: MouseButtonEvent(btn) {}
EVENT_STRINGIFY("MouseButtonPressEvent %d", m_btn)
@ -70,7 +70,7 @@ namespace Bk
class MouseButtonReleaseEvent : public MouseButtonEvent
{
public:
MouseButtonReleaseEvent(MouseCode btn)
MouseButtonReleaseEvent(Code btn)
: MouseButtonEvent(btn) {}
EVENT_STRINGIFY("MouseButtonReleaseEvent %d", m_btn)

@ -1,17 +1,17 @@
#pragma once
#include <bkpch.h>
#include "bakatools/container/types.h"
#include "event.h"
namespace Bk {
class WindowResizeEvent : public Event
{
public:
WindowResizeEvent(uint width, uint height)
WindowResizeEvent(u32 width, u32 height)
: p_width(width), p_height(height) {};
uint get_width() const { return p_width; }
uint get_height() const { return p_height; }
u32 GetWidth() const { return p_width; }
u32 GetHeight() const { return p_height; }
EVENT_STRINGIFY("WindowResizeEvent : %d %d", p_width, p_height)
@ -19,8 +19,8 @@ namespace Bk {
EVENT_CLASS_CATEGORY(AppCategory)
private:
uint p_width;
uint p_height;
u32 p_width;
u32 p_height;
};
class WindowCloseEvent : public Event

@ -0,0 +1,5 @@
#include <misc/cpp/imgui_stdlib.cpp>
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#include <backends/imgui_impl_glfw.cpp>
#include <backends/imgui_impl_opengl3.cpp>

@ -0,0 +1,77 @@
#include "imgui_layer.h"
#include "bakara/core/application.h"
#include <imgui.h>
#include <imgui_internal.h>
#include <backends/imgui_impl_glfw.h>
#include <backends/imgui_impl_opengl3.h>
#include <GLFW/glfw3.h>
#include <glad/glad.h>
namespace Bk {
void ImguiLayer::OnAttach()
{
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = NULL;
#if defined(BK_IMGUI_DOCKING)
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons;
io.ConfigViewportsNoAutoMerge = true;
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
#endif
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
Application& app = Application::Get();
GLFWwindow* window = static_cast<GLFWwindow*>(app.GetWindow().GetNativeWindow());
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 420");
}
void ImguiLayer::OnDetach()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void ImguiLayer::Begin()
{
ImGuiIO& io = ImGui::GetIO();
Application& app = Application::Get();
io.DisplaySize = ImVec2((float)app.GetWindow().GetWidth(), (float)app.GetWindow().GetHeight());
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void ImguiLayer::End()
{
// Rendering
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
#if defined(BK_IMGUI_DOCKING)
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
GLFWwindow* backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context);
}
#endif
}
}

@ -0,0 +1,18 @@
#pragma once
#include <imgui.h>
#include "bakara/core/layer.h"
namespace Bk {
class ImguiLayer : public Layer
{
public:
ImguiLayer()
: Layer("Imgui") {}
void OnAttach() override;
void OnDetach() override;
void Begin();
void End();
};
}

@ -0,0 +1,18 @@
#pragma once
#include "controller_codes.h"
namespace Bk
{
class Controller {
public:
virtual void Update() = 0;
virtual float Axes(Code axis) = 0;
virtual unsigned char Button(Code button) = 0;
virtual int GetAxesCount() = 0;
virtual int GetButtonCount() = 0;
virtual bool IsPresent() = 0;
virtual const char* GetName() = 0;
};
}

@ -0,0 +1,47 @@
#pragma once
#include <cstdint>
namespace Bk {
/*! \typedef Bk::ControllerCode
Unsigned integer representing a unique controller button
*/
using Code = uint16_t;
/*! \enum Bk::ControllerButton
Enumerator made to bind every controller buttons with a Bk::ControllerCode
*/
typedef enum : Code
{
BTN_DOWN = 0, //!< Cross, A
BTN_LEFT = 1, //!< Square, X
BTN_UP = 2, //!< Triangle, Y
BTN_RIGHT = 3, //!< Circle, B
SHOULDER_LEFT = 4, //!< L1, LB
SHOULDER_RIGHT = 5, //!< R1, RB
TRIGGER_LEFT = 6, //!< L2, LT
TRIGGER_RIGHT = 7, //!< R2, RT
SELECT = 8, //!< Share, Address
START = 9, //!< Options, Menu
LEFT_STICK = 10, //!< L3, LS
RIGHT_STICK = 11, //!< R3, RS
HOME = 12, //!< Home, Home
CLICK = 13, //!< Touch pad, n/a
DPAD_UP = 14, //!< Dpad up, Dpad up
DPAD_RIGHT = 15, //!< Dpad right, Dpad right
DPAD_DOWN = 16, //!< Dpad down, Dpad down
DPAD_LEFT = 17, //!< Dpad left, Dpad left
} ControllerButton;
/*! \enum Bk::ControllerJoystick
Enum made to bind every controller axes with a Bk::ControllerAxesCode
*/
typedef enum : Code
{
AXES_LEFT_STICK_X = 0,
AXES_LEFT_STICK_Y = 1,
AXES_RIGHT_STICK_X = 2,
AXES_LEFT_TRIGGER = 3,
AXES_RIGHT_TRIGGER = 4,
AXES_RIGHT_STICK_Y = 5,
} ControllerAxes;
}

@ -0,0 +1,10 @@
#pragma once
/*! \file io_codes.h
Input codes abstraction to be able to use different window api.
Can be converte in the good code for the window api by using a lookup table or defines at compilation.
*/
#include "key_codes.h"
#include "mouse_codes.h"
#include "controller_codes.h"

@ -1,21 +1,17 @@
#pragma once
/*! \file io_codes.h
Input codes abstraction to be able to use different window api.
Can be converte in the good code for the window api by using a lookup table or defines at compilation.
*/
#include <cstdint>
namespace Bk {
/*! \typedef Bk::KeyCode
Unsigned integer representing a unique keyboard key
*/
using KeyCode = uint16_t;
using Code = uint16_t;
/*! \enum Bk::KeyCodes
Enumerator made to bind every keyboard keys with a Bk::KeyCode
*/
typedef enum : KeyCode
typedef enum : Code
{
Space = 32, /*!< _ */
Apostrophe = 39, /*!< ' */
@ -145,77 +141,5 @@ namespace Bk {
RightAlt = 346,
RightSuper = 347,
Menu = 348
} KeyCodes;
/*! \typedef Bk::MouseCode
Unsigned integer representing a unique mouse button
*/
using MouseCode = uint16_t;
/*! \enum Bk::MouseCodes
Enumerator made to bind every mouse buttons with a Bk::MouseCode
*/
typedef enum : MouseCode
{
Button0 = 0, /*!< Button left */
Button1 = 1, /*!< Button right */
Button2 = 2, /*!< Button middle */
Button3 = 3, /*!< Macro1 */
Button4 = 4, /*!< Macro2 */
Button5 = 5, /*!< Macro3 */
Button6 = 6, /*!< Macro4 */
Button7 = 7, /*!< Button last */
ButtonLast = Button7,
ButtonLeft = Button0,
ButtonRight = Button1,
ButtonMiddle = Button2
} MouseCodes;
/*! \typedef Bk::ControllerCode
Unsigned integer representing a unique controller button
*/
using ControllerCode = uint16_t;
/*! \typedef Bk::ControllerAxesCode
Unsigned integer representing a unique controller axe
*/
using ControllerAxesCode = uint16_t;
/*! \enum Bk::ControllerButton
Enumerator made to bind every controller buttons with a Bk::ControllerCode
*/
typedef enum : ControllerCode
{
BTN_DOWN = 0, //!< Cross, A
BTN_LEFT = 1, //!< Square, X
BTN_UP = 2, //!< Triangle, Y
BTN_RIGHT = 3, //!< Circle, B
SHOULDER_LEFT = 4, //!< L1, LB
SHOULDER_RIGHT = 5, //!< R1, RB
TRIGGER_LEFT = 6, //!< L2, LT
TRIGGER_RIGHT = 7, //!< R2, RT
SELECT = 8, //!< Share, Address
START = 9, //!< Options, Menu
LEFT_STICK = 10, //!< L3, LS
RIGHT_STICK = 11, //!< R3, RS
HOME = 12, //!< Home, Home
CLICK = 13, //!< Touch pad, n/a
DPAD_UP = 14, //!< Dpad up, Dpad up
DPAD_RIGHT = 15, //!< Dpad right, Dpad right
DPAD_DOWN = 16, //!< Dpad down, Dpad down
DPAD_LEFT = 17, //!< Dpad left, Dpad left
} ControllerButton;
/*! \enum Bk::ControllerJoystick
Enum made to bind every controller axes with a Bk::ControllerAxesCode
*/
typedef enum : ControllerAxesCode
{
AXES_LEFT_STICK_X = 0,
AXES_LEFT_STICK_Y = 1,
AXES_RIGHT_STICK_X = 2,
AXES_LEFT_TRIGGER = 3,
AXES_RIGHT_TRIGGER = 4,
AXES_RIGHT_STICK_Y = 5,
} ControllerJoystick;
} KeyCode;
}

@ -0,0 +1,14 @@
#pragma once
#include "key_codes.h"
namespace Bk
{
class Keyboard
{
public:
static bool KeyRepeat(Code key);
static bool KeyUp(Code key);
static bool KeyDown(Code key);
};
}

@ -0,0 +1,15 @@
#pragma once
#include "bakara/math/types.h"
#include "mouse_codes.h"
namespace Bk
{
class Mouse {
public:
static Vec2 GetPosition();
static bool ButtonUp(Code button);
static bool ButtonDown(Code button);
static bool ButtonRepeat(Code button);
};
}

@ -0,0 +1,30 @@
#pragma once
#include <cstdint>
namespace Bk {
/*! \typedef Bk::MouseCode
Unsigned integer representing a unique mouse button
*/
using Code = uint16_t;
/*! \enum Bk::MouseCodes
Enumerator made to bind every mouse buttons with a Bk::MouseCode
*/
typedef enum : Code
{
Button0 = 0, /*!< Button left */
Button1 = 1, /*!< Button right */
Button2 = 2, /*!< Button middle */
Button3 = 3, /*!< Macro1 */
Button4 = 4, /*!< Macro2 */
Button5 = 5, /*!< Macro3 */
Button6 = 6, /*!< Macro4 */
Button7 = 7, /*!< Button last */
ButtonLast = Button7,
ButtonLeft = Button0,
ButtonRight = Button1,
ButtonMiddle = Button2
} MouseCode;
}

@ -5,14 +5,19 @@ Math types alias file used to abstract math types and not depend on any library.
As long as it's implemented here.
*/
#include <bakara/math/mathpch.h>
#include "glm/fwd.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
namespace Bk
{
/*! \typedef Bk::uint
Simplefied name for unsigned int
*/
using uint = unsigned int;
namespace Math = glm;
using Quaterion = glm::quat;
using Color = glm::vec4;
/*! \typedef Bk::Vec2
Wrapper around glm::vec2
*/

@ -0,0 +1,30 @@
#include "buffer.h"
#include "bakara/renderer/renderer.h"
#include "bakatools/container/types.h"
#include "bakatools/logging/assert.h"
#include "platforms/opengl/opengl_buffer.h"
namespace Bk
{
Ref<VertexBuffer> VertexBuffer::Create(float *vertices, u32 size)
{
switch (Renderer::GetAPI())
{
case Renderer::API::None: BK_MSG_ASSERT(false, "API not supported"); return nullptr;
case Renderer::API::Opengl: return CreateRef<Platform::OpenglVertexBuffer>(vertices, size);
}
BK_MSG_ASSERT(false, "API not supported");
return nullptr;
}
Ref<IndexBuffer> IndexBuffer::Create(u32* indices, u32 count)
{
switch (Renderer::GetAPI())
{
case Renderer::API::None: BK_MSG_ASSERT(false, "API not supported"); return nullptr;
case Renderer::API::Opengl: return CreateRef<Platform::OpenglIndexBuffer>(indices, count);
}
BK_MSG_ASSERT(false, "API not supported");
return nullptr;
}
}

@ -0,0 +1,27 @@
#pragma once
#include "bakara/renderer/buffer_layout.h"
#include "bakatools/container/types.h"
namespace Bk
{
class VertexBuffer
{
public:
virtual ~VertexBuffer() {}
virtual void Bind() = 0;
virtual void Unbind() = 0;
virtual void SetLayout(BufferLayout layout) = 0;
virtual BufferLayout& GetLayout() = 0;
static Ref<VertexBuffer> Create(float* vertices, u32 size);
};
class IndexBuffer
{
public:
virtual ~IndexBuffer() {}
virtual void Bind() = 0;
virtual void Unbind() = 0;
virtual u32 GetCount() = 0;
static Ref<IndexBuffer> Create(u32* indices, u32 count);
};
}

@ -0,0 +1,56 @@
#include "buffer_layout.h"
namespace Bk
{
u32 ShaderType::Size()
{
switch (type)
{
case None: return 0;
case Bool: return 1;
case Int: return 4;
case Int2: return 4 * 2;
case Int3: return 4 * 3;
case Int4: return 4 * 4;
case Float: return 4;
case Float2: return 4 * 2;
case Float3: return 4 * 3;
case Float4: return 4 * 4;
case Mat3: return 4 * 3 * 3;
case Mat4: return 4 * 4 * 4;
}
}
u32 ShaderType::Count()
{
switch (type)
{
case None: return 0;
case Bool: return 1;
case Int: return 1;
case Int2: return 2;
case Int3: return 3;
case Int4: return 4;
case Float: return 1;
case Float2: return 2;
case Float3: return 3;
case Float4: return 4;
case Mat3: return 3 * 3;
case Mat4: return 4 * 4;
}
}
void BufferLayout::CalculteOffsetAndStride()
{
u32 offset = 0;
stride = 0;
for(auto& element : elements)
{
element.offset = offset;
offset += element.type.Size();
stride += element.type.Size();
}
}
}

@ -0,0 +1,70 @@
#pragma once
#include "bakatools/container/types.h"
#include <initializer_list>
#include <vector>
#include <string>
namespace Bk
{
class ShaderType
{
public:
enum Type : u8
{
None = 0,
Bool, Int, Int2, Int3, Int4,
Float, Float2, Float3, Float4,
Mat3, Mat4
};
ShaderType() : type(None) {}
ShaderType(Type type) : type(type) {}
ShaderType& operator=(Type value) { type = value; return *this; }
operator Type() const { return type; }
bool operator==(Type type) { return type == this->type; }
bool operator!=(Type type) { return type != this->type; }
bool operator==(ShaderType value) { return value.type == this->type; }
bool operator!=(ShaderType value) { return value.type != this->type; }
u32 Size();
u32 Count();
private:
Type type;
};
struct BufferElement
{
std::string name;
u32 offset;
ShaderType type;
bool normelized;
BufferElement() = default;
BufferElement(std::string name, ShaderType type, bool normelized = false)
: name(name), type(type) {}
BufferElement(ShaderType type, std::string name, bool normelized = false)
: name(name), type(type), normelized(normelized) {}
};
class BufferLayout
{
public:
BufferLayout() = default;
BufferLayout(const std::initializer_list<BufferElement>& elements)
: elements(elements) { CalculteOffsetAndStride(); }
inline u32 GetStride() { return stride; }
inline std::vector<BufferElement>& GetElements() { return elements; }
std::vector<BufferElement>::iterator begin() { return elements.begin(); }
std::vector<BufferElement>::iterator end() { return elements.end(); }
private:
void CalculteOffsetAndStride();
std::vector<BufferElement> elements;
u32 stride;
};
}

@ -0,0 +1,29 @@
#include "ortho_camera.h"
#include "bakara/math/types.h"
#include "glm/ext/matrix_clip_space.hpp"
#include "glm/ext/matrix_transform.hpp"
#include "glm/matrix.hpp"
#include "glm/trigonometric.hpp"
namespace Bk
{
OrthoCamera::OrthoCamera(float left, float right, float bottom, float top)
: projection(Math::ortho(left, right, bottom, top, -10.0f, 10.0f))
{
RecalculateView();
}
void OrthoCamera::SetProjection(float left, float right, float bottom, float top)
{
projection = Math::ortho(left, right, bottom, top, -10.0f, 10.0f);
viewProjection = projection * view;
}
void OrthoCamera::RecalculateView()
{
Mat4 transform = Math::translate(Mat4(1.0f), position);
transform = Math::rotate(transform, Math::radians(rotation) , Vec3(0.0f, 0.0f, 1.0f));
view = Math::inverse(transform);
viewProjection = projection * view;
}
}

@ -0,0 +1,31 @@
#pragma once
#include "bakara/math/types.h"
namespace Bk
{
class OrthoCamera
{
public:
OrthoCamera(float left, float right, float bottom, float top);
void SetPosition(Vec3 position) { this->position = position; RecalculateView(); }
const Vec3& GetPosition() const { return position; }
void SetRotation(float rotation) { this->rotation = rotation; RecalculateView(); }
float GetRotaion() const { return rotation; }
const Mat4 GetView() const { return view; }
void SetProjection(float left, float right, float bottom, float top);
const Mat4 GetProjection() const { return projection; }
const Mat4 GetViewProjection() const { return viewProjection; }
private:
void RecalculateView();
Mat4 view;
Mat4 projection;
Mat4 viewProjection;
Vec3 position = { 0.0f, 0.0f, 0.0f };
float rotation = 0.0f;
};
}

@ -0,0 +1,76 @@
#include "ortho_camera_controller.h"
#include "bakara/events/dispacher.h"
#include "bakara/events/event.h"
#include "bakara/events/window_event.h"
#include "bakara/io/keyboard.h"
#include "glm/trigonometric.hpp"
#include <cmath>
namespace Bk
{
OrthoCameraController::OrthoCameraController(float aspectRatio, bool rotation, bool zoom)
: aspectRatio(aspectRatio),
camera(-aspectRatio * zoomLevel, aspectRatio * zoomLevel, -zoomLevel, zoomLevel),
rotation(rotation), zoom(zoom) {}
void OrthoCameraController::OnEvent(Event& e)
{
EventDispatcher dispatcher(e);
dispatcher.dispatch<WindowResizeEvent>(BK_BIND_DISPACHER_FN(WindowResizeEvent, OnWindowResize));
dispatcher.dispatch<MouseScrollEvent>(BK_BIND_DISPACHER_FN(MouseScrollEvent, OnMouseScroll));
}
void OrthoCameraController::OnUpdate(DeltaTime dt)
{
if (rotation)
{
if(Keyboard::KeyDown(KeyCode::Q))
cameraRotation -= rotationSpeed * dt;
if(Keyboard::KeyDown(KeyCode::E))
cameraRotation += rotationSpeed * dt;
camera.SetRotation(cameraRotation);
}
if(Keyboard::KeyDown(KeyCode::W))
{
cameraPosition.x += -std::sin(Math::radians(cameraRotation)) * moveSpeed * dt;
cameraPosition.y += std::cos(Math::radians(cameraRotation)) * moveSpeed * dt;
}
if(Keyboard::KeyDown(KeyCode::S))
{
cameraPosition.x -= -std::sin(Math::radians(cameraRotation)) * moveSpeed * dt;
cameraPosition.y -= std::cos(Math::radians(cameraRotation)) * moveSpeed * dt;
}
if(Keyboard::KeyDown(KeyCode::D))
{
cameraPosition.x += std::cos(Math::radians(cameraRotation)) * moveSpeed * dt;
cameraPosition.y += std::sin(Math::radians(cameraRotation)) * moveSpeed * dt;
}
if(Keyboard::KeyDown(KeyCode::A))
{
cameraPosition.x -= std::cos(Math::radians(cameraRotation)) * moveSpeed * dt;
cameraPosition.y -= std::sin(Math::radians(cameraRotation)) * moveSpeed * dt;
}
camera.SetPosition(cameraPosition);
}
bool OrthoCameraController::OnMouseScroll(MouseScrollEvent& e)
{
if (zoom)
{
zoomLevel -= e.GetDY() * 0.01;
zoomLevel = std::max(zoomLevel, 0.5f);
zoomLevel = std::min(zoomLevel, 10.0f);
camera.SetProjection(-aspectRatio * zoomLevel, aspectRatio * zoomLevel, -zoomLevel, zoomLevel);
return true;
}
return false;
}
bool OrthoCameraController::OnWindowResize(WindowResizeEvent& e)
{
aspectRatio = (float)e.GetWidth() / (float)e.GetHeight();
camera.SetProjection(-aspectRatio * zoomLevel, aspectRatio * zoomLevel, -zoomLevel, zoomLevel);
return false;
}
}

@ -0,0 +1,41 @@
#pragma once
#include "bakara/core/deltatime.h"
#include "bakara/events/event.h"
#include "bakara/events/mouse_event.h"
#include "bakara/events/window_event.h"
#include "ortho_camera.h"
namespace Bk
{
class OrthoCameraController
{
public:
OrthoCameraController(float aspectRatio, bool rotation = false, bool zoom = false);
void OnUpdate(DeltaTime dt);
void OnEvent(Event& e);
const OrthoCamera& GetCamera() { return camera; }
void SetMoveSpeed(float moveSpeed) { this->moveSpeed = moveSpeed; }
void SetRotationSpeed(float rotationSpeed) { this->rotationSpeed = rotationSpeed; }
void SetZoomLevel(float level) { zoomLevel = level; }
void SetPosition(Vec3 cameraPosition) { this->cameraPosition = cameraPosition; }
private:
float aspectRatio;
float zoomLevel = 1.0f;
bool rotation, zoom;
float cameraRotation = 0.0f;
Vec3 cameraPosition = { 0, 0, 0 };
float moveSpeed = 1.0f;
float rotationSpeed = 1.0f;
OrthoCamera camera;
bool OnMouseScroll(MouseScrollEvent& e);
bool OnWindowResize(WindowResizeEvent& e);
};
}

@ -0,0 +1,18 @@
#include "graphics_context.h"
#include "bakara/renderer/renderer.h"
#include "bakatools/logging/assert.h"
#include "platforms/opengl/opengl_context.h"
namespace Bk
{
Scope<GraphicsContext> GraphicsContext::Create(void *window_handle)
{
switch (Renderer::GetAPI())
{
case Renderer::API::None: BK_MSG_ASSERT(false, "API not supported"); return nullptr;
case Renderer::API::Opengl: return CreateScope<Platform::OpenglContext>(window_handle);
}
BK_MSG_ASSERT(false, "API not supported");
return nullptr;
}
}

@ -0,0 +1,15 @@
#pragma once
#include "bakatools/container/types.h"
namespace Bk
{
class GraphicsContext
{
public:
virtual ~GraphicsContext() {}
virtual void Init() = 0;
virtual void SwapBuffers() = 0;
static Scope<GraphicsContext> Create(void* window_handle);
};
}

@ -0,0 +1,8 @@
#include "render_command.h"
#include "bakara/renderer/renderer_api.h"
#include "platforms/opengl/opengl_renderer_api.h"
namespace Bk
{
RendererAPI* RenderCommand::rendererAPI = new OpenglRendererAPI();
}

@ -0,0 +1,20 @@
#pragma once
#include "bakara/math/types.h"
#include "bakara/renderer/renderer_api.h"
#include "bakara/renderer/vertex_array.h"
namespace Bk
{
class RenderCommand
{
public:
static inline void Init() { rendererAPI->Init(); }
static inline void Clear(Vec4 color) { rendererAPI->Clear(color.r, color.g, color.b, color.a); }
static inline void Clear(float red, float green, float blue, float alpha) { rendererAPI->Clear(red, green, blue, alpha); }
static inline void SetViewport(u32 width, u32 height) { rendererAPI->SetViewport(width, height); }
static inline void DrawIndexed(Ref<VertexArray> va) { rendererAPI->DrawIndexed(va); }
private:
static RendererAPI* rendererAPI;
};
}

@ -0,0 +1,39 @@
#include "renderer.h"
#include "bakara/renderer/cameras/ortho_camera.h"
#include "bakara/renderer/render_command.h"
#include "bakara/renderer/renderer2D.h"
namespace Bk
{
Renderer::API Renderer::s_RenderAPI = Renderer::API::Opengl;
Renderer::Storage* Renderer::data = new Renderer::Storage();
void Renderer::Init()
{
RenderCommand::Init();
Renderer2D::Init();
}
void Renderer::ResizeFrame(u32 width, u32 height)
{
RenderCommand::SetViewport(width, height);
}
void Renderer::BeginScene(const OrthoCamera& camera)
{
data->viewProjection = camera.GetViewProjection();
}
void Renderer::EndScene()
{
}
void Renderer::Submit(Ref<VertexArray> va, Ref<Shader> shader, Mat4 transform)
{
va->Bind();
shader->Bind();
shader->Set("u_ViewProjection", data->viewProjection);
shader->Set("u_Transform", transform);
RenderCommand::DrawIndexed(va);
}
}

@ -0,0 +1,38 @@
#pragma once
#include "bakara/math/types.h"
#include "bakara/renderer/cameras/ortho_camera.h"
#include "bakara/renderer/shader.h"
#include "bakara/renderer/vertex_array.h"
#include "bakatools/container/types.h"
namespace Bk
{
class Renderer
{
public:
enum class API
{
None = 0,
Opengl = 1,
};
static API GetAPI() { return s_RenderAPI; }
static void Init();
static void ResizeFrame(u32 width, u32 height);
static void BeginScene(const OrthoCamera& camera);
static void EndScene();
static void Submit(Ref<VertexArray> va, Ref<Shader> shader, Mat4 transform = Mat4(1.0f));
private:
struct Storage
{
Mat4 viewProjection;
};
static Storage* data;
static API s_RenderAPI;
};
}

@ -0,0 +1,81 @@
#include "renderer2D.h"
#include "bakara/renderer/buffer.h"
#include "bakara/renderer/buffer_layout.h"
#include "bakara/renderer/render_command.h"
#include "bakara/renderer/texture.h"
namespace Bk
{
Renderer2D::Storage* Renderer2D::data = new Renderer2D::Storage();
void Renderer2D::Init()
{
data->shaderLib.Load("assets/shaders/flatColor.glsl");
data->shaderLib.Load("assets/shaders/texture.glsl");
data->squareVA = VertexArray::Create();
float squareVertices[5 * 4] = {
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 0.0f, 1.0f
};
Ref<VertexBuffer> squareVB = VertexBuffer::Create(squareVertices, sizeof(squareVertices));
squareVB->SetLayout({
{ ShaderType::Float3, "a_Position" },
{ ShaderType::Float2, "a_TextCord" }
});
data->squareVA->AddVertexBuffer(squareVB);
u32 squareIndices[6] = { 0, 1, 2, 0, 2, 3 };
data->squareVA->SetIndexbuffer(IndexBuffer::Create(squareIndices, sizeof(squareIndices) / sizeof(u32)));
}
void Renderer2D::Shutdown()
{
delete data;
}
void Renderer2D::BeginScene(const OrthoCamera &camera)
{
data->viewProjection = camera.GetViewProjection();
}
void Renderer2D::EndScene()
{
}
void Renderer2D::DrawQuad(const Vec2& position, const Vec2& size, const Color& color)
{
Renderer2D::DrawQuad(Vec3(position, 0), size, color);
}
void Renderer2D::DrawQuad(const Vec3& position, const Vec2& size, const Color& color)
{
Ref<Shader> shader = data->shaderLib["flatColor"];
data->squareVA->Bind();
shader->Bind();
shader->Set("u_FlatColor", color);
shader->Set("u_ViewProjection", data->viewProjection);
shader->Set("u_Transform", Math::scale(Math::translate(Mat4(1.0f), position), Vec3(size, 0)));
RenderCommand::DrawIndexed(data->squareVA);
}
void Renderer2D::DrawQuad(const Vec2& position, const Vec2& size, const Ref<Texture2D>& texture)
{
Renderer2D::DrawQuad(Vec3(position, 0), size, texture);
}
void Renderer2D::DrawQuad(const Vec3& position, const Vec2& size, const Ref<Texture2D>& texture)
{
Ref<Shader> shader = data->shaderLib["texture"];
data->squareVA->Bind();
texture->Bind();
shader->Bind();
shader->Set("u_Texture", 0);
shader->Set("u_ViewProjection", data->viewProjection);
shader->Set("u_Transform", Math::scale(Math::translate(Mat4(1.0f), position), Vec3(size, 0)));
RenderCommand::DrawIndexed(data->squareVA);
}
}

@ -0,0 +1,33 @@
#pragma once
#include "bakara/renderer/shader.h"
#include "bakara/renderer/texture.h"
#include "bakara/renderer/vertex_array.h"
#include "cameras/ortho_camera.h"
namespace Bk
{
class Renderer2D
{
public:
static void Init();
static void Shutdown();
static void BeginScene(const OrthoCamera& camera);
static void EndScene();
static void DrawQuad(const Vec2& position, const Vec2& size, const Color& color);
static void DrawQuad(const Vec3& position, const Vec2& size, const Color& color);
static void DrawQuad(const Vec2& position, const Vec2& size, const Ref<Texture2D>& texture);
static void DrawQuad(const Vec3& position, const Vec2& size, const Ref<Texture2D>& texture);
private:
struct Storage
{
Mat4 viewProjection;
Ref<VertexArray> squareVA;
ShaderLibrary shaderLib;
};
static Storage* data;
};
}

@ -0,0 +1,17 @@
#pragma once
#include "bakara/renderer/vertex_array.h"
namespace Bk
{
class RendererAPI
{
public:
virtual ~RendererAPI() {}
virtual void Init() = 0;
virtual void Clear(float red, float green, float blue, float alpha) = 0;
virtual void SetViewport(u32 width, u32 height) = 0;
virtual void DrawIndexed(Ref<VertexArray> va) = 0;
};
}

@ -0,0 +1,60 @@
#include "shader.h"
#include "bakara/renderer/renderer.h"
#include "bakatools/logging/assert.h"
#include "platforms/opengl/opengl_shader.h"
namespace Bk
{
Ref<Shader> Shader::Create(const std::string& name, const std::string& vertexSrc, const std::string& fragSrc)
{
switch(Renderer::GetAPI())
{
case Renderer::API::None: BK_MSG_ASSERT(false, "API not supported"); return nullptr;
case Renderer::API::Opengl: return CreateRef<Platform::OpenglShader>(name, vertexSrc, fragSrc);
}
BK_MSG_ASSERT(false, "API not supported");
return nullptr;
}
Ref<Shader> Shader::Create(const std::string& filePath)
{
switch(Renderer::GetAPI())
{
case Renderer::API::None: BK_MSG_ASSERT(false, "API not supported"); return nullptr;
case Renderer::API::Opengl: return CreateRef<Platform::OpenglShader>(filePath);
}
BK_MSG_ASSERT(false, "API not supported");
return nullptr;
}
void ShaderLibrary::Add(const std::string& name, const Ref<Shader>& shader)
{
BK_CORE_MSG_ASSERT(!Exists(name), "Shader already exists in library")
shaders[name] = shader;
}
void ShaderLibrary::Add(const Ref<Shader>& shader)
{
const auto& name = shader->GetName();
Add(shader->GetName(), shader);
}
Ref<Shader> ShaderLibrary::Load(const std::string& filePath)
{
Ref<Shader> shader = Shader::Create(filePath);
Add(shader);
return shader;
}
Ref<Shader> ShaderLibrary::Load(const std::string& name, const std::string filePath)
{
Ref<Shader> shader = Shader::Create(filePath);
Add(name, shader);
return shader;
}
Ref<Shader> ShaderLibrary::Get(const std::string& name)
{
BK_CORE_MSG_ASSERT(Exists(name), "Shader not found")
return shaders[name];
}
}

@ -0,0 +1,49 @@
#pragma once
#include "bakara/math/types.h"
#include "bakatools/container/types.h"
#include <string>
#include <unordered_map>
namespace Bk
{
class Shader
{
public:
virtual ~Shader() {}
virtual const std::string& GetName() = 0;
virtual void Bind() = 0;
virtual void Unbind() = 0;
virtual void Set(const std::string name, int val) = 0;
virtual void Set(const std::string name, bool val) = 0;
virtual void Set(const std::string name, float val) = 0;
virtual void Set(const std::string name, float v1, float v2, float v3) = 0;
virtual void Set(const std::string name, Vec3 v) = 0;
virtual void Set(const std::string name, float v1, float v2, float v3, float v4) = 0;
virtual void Set(const std::string name, Vec4 v) = 0;
virtual void Set(const std::string name, Mat3 val) = 0;
virtual void Set(const std::string name, Mat4 val) = 0;
static Ref<Shader> Create(const std::string& name, const std::string& vertexSrc, const std::string& fragSrc);
static Ref<Shader> Create(const std::string& filePath);
};
class ShaderLibrary
{
public:
inline bool Exists(const std::string& name) { return shaders.find(name) != shaders.end(); }
void Add(const std::string& name, const Ref<Shader>& shader);
void Add(const Ref<Shader>& shader);
Ref<Shader> Load(const std::string& filePath);
Ref<Shader> Load(const std::string& name, const std::string filePath);
Ref<Shader> Get(const std::string& name);
inline Ref<Shader> operator[](const std::string& name) { return Get(name); }
private:
std::unordered_map<std::string, Ref<Shader>> shaders;
};
}

@ -0,0 +1,18 @@
#include "bakara/renderer/renderer.h"
#include "bakatools/logging/assert.h"
#include "texture.h"
#include "platforms/opengl/opengl_texture.h"
namespace Bk
{
Ref<Texture2D> Texture2D::Create(const std::string& filePath)
{
switch (Renderer::GetAPI())
{
case Renderer::API::None: BK_MSG_ASSERT(false, "API not supported"); return nullptr;
case Renderer::API::Opengl: return CreateRef<Platform::OpenglTexture2D>(filePath);
}
BK_MSG_ASSERT(false, "API not supported");
return nullptr;
}
}

@ -0,0 +1,22 @@
#pragma once
#include "bakatools/container/types.h"
#include <string>
namespace Bk
{
class Texture
{
public:
virtual ~Texture() {}
virtual u32 GetWidth() = 0;
virtual u32 GetHeight() = 0;
virtual void Bind(u32 slot = 0) = 0;
};
class Texture2D : public Texture
{
public:
static Ref<Texture2D> Create(const std::string& filePath);
};
}

@ -0,0 +1,18 @@
#include "bakara/renderer/renderer.h"
#include "bakatools/logging/assert.h"
#include "vertex_array.h"
#include "platforms/opengl/opengl_vertex_array.h"
namespace Bk
{
Ref<VertexArray> VertexArray::Create()
{
switch (Renderer::GetAPI())
{
case Renderer::API::None: BK_MSG_ASSERT(false, "API not supported"); return nullptr;
case Renderer::API::Opengl: return CreateRef<Platform::OpenglVertexArray>();
}
BK_MSG_ASSERT(false, "API not supported");
return nullptr;
}
}

@ -0,0 +1,21 @@
#pragma once
#include "bakara/renderer/buffer.h"
#include "bakatools/container/types.h"
namespace Bk
{
class VertexArray
{
public:
virtual ~VertexArray() {}
virtual void Bind() = 0;
virtual void Unbind() = 0;
virtual void AddVertexBuffer(Ref<VertexBuffer> buf) = 0;
virtual void SetIndexbuffer(Ref<IndexBuffer> buf) = 0;
virtual std::vector<Ref<VertexBuffer>> GetVertexBuffers() = 0;
virtual Ref<IndexBuffer> GetIndexbuffer() = 0;
static Ref<VertexArray> Create();
};
}

@ -0,0 +1,4 @@
#include "glfw_controller.h"
#include <GLFW/glfw3.h>

@ -0,0 +1,35 @@
#pragma once
#include "bakara/io/controller.h"
namespace Bk
{
namespace Platform
{
class ControllerGLFW : public Controller
{
public:
ControllerGLFW() = delete;
ControllerGLFW(int i);
void Update() override;
float Axes(Code axis) override;
unsigned char Button(Code button) override;
int GetAxesCount() override;
int GetButtonCount() override;
bool IsPresent() override;
const char* GetName() override;
private:
int present;
int id;
const char* name;
int axesCount;
const float* axes;
int buttonCount;
const unsigned char* buttons;
};
}
}

@ -0,0 +1,27 @@
#include "bakara/io/keyboard.h"
#include "bakara/core/application.h"
#include <GLFW/glfw3.h>
namespace Bk
{
bool Keyboard::KeyDown(Code key)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetKey(window, static_cast<int32_t>(key));
return state == GLFW_PRESS;
}
bool Keyboard::KeyUp(Code key)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetKey(window, static_cast<int32_t>(key));
return state == GLFW_RELEASE;
}
bool Keyboard::KeyRepeat(Code key)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetKey(window, static_cast<int32_t>(key));
return state == GLFW_REPEAT;
}
}

@ -0,0 +1,36 @@
#include "bakara/io/mouse.h"
#include "bakara/core/application.h"
#include <GLFW/glfw3.h>
namespace Bk
{
Vec2 Mouse::GetPosition()
{
auto& window_handle = Application::Get().GetWindow();
auto* window = static_cast<GLFWwindow*>(window_handle.GetNativeWindow());
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
return { (float)xpos - (float)window_handle.GetWidth()/2, (float)ypos - (float)window_handle.GetHeight()/2 };
}
bool Mouse::ButtonUp(Code button)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetMouseButton(window, static_cast<int32_t>(button));
return state == GLFW_RELEASE;
}
bool Mouse::ButtonDown(Code button)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetMouseButton(window, static_cast<int32_t>(button));
return state == GLFW_PRESS;
}
bool Mouse::ButtonRepeat(Code button)
{
auto* window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetMouseButton(window, static_cast<int32_t>(button));
return state == GLFW_REPEAT;
}
}

@ -1,73 +1,74 @@
#include <glad/glad.h>
#include "win_glfw.h"
#include "glfw_window.h"
#include "bakara/core/deltatime.h"
#include "bakara/events/key_event.h"
#include "bakara/events/mouse_event.h"
#include "bakara/events/window_event.h"
#include "bakara/renderer/graphics_context.h"
#include "bakatools/logging/assert.h"
#include <GLFW/glfw3.h>
namespace Bk {
Window* Window::create_window(const WindowProps& props)
Window* Window::CreateWindow(const WindowProps& props)
{
return new Plaform::WinGLFW(props);
return new Platform::GlfwWindow(props);
}
namespace Plaform {
static uint p_glfw_initialized = 0;
namespace Platform {
static uint p_glfw_Initialized = 0;
static void glfw_error_callback(int error, const char* description)
{
BK_CORE_CRITICAL("GLFW Error ({0}) {1}", error, description);
}
WinGLFW::WinGLFW(const WindowProps& props)
GlfwWindow::GlfwWindow(const WindowProps& props)
{
p_data.title = props.title;
p_data.width = props.width;
p_data.height = props.height;
init();
Init();
}
WinGLFW::~WinGLFW()
GlfwWindow::~GlfwWindow()
{
close();
Close();
}
void WinGLFW::init()
void GlfwWindow::Init()
{
h_is_open = true;
BK_CORE_INFO("Creating window : {0} ({1}, {2})", p_data.title, p_data.width, p_data.height);
if (!p_glfw_initialized++)
BK_CORE_INFO("Creating window '{0}' ({1}, {2})", p_data.title, p_data.width, p_data.height);
if (!p_glfw_Initialized++)
{
int success = glfwInit();
BK_MSG_ASSERT(success, "Couldn't initialize glfw!")
BK_CORE_MSG_ASSERT(success, "Couldn't Initialize glfw!")
glfwSetErrorCallback(glfw_error_callback);
}
p_window = glfwCreateWindow((int)p_data.width, (int)p_data.height, p_data.title.c_str(), nullptr, nullptr);
glfwMakeContextCurrent(p_window);
int success = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
BK_CORE_MSG_ASSERT(success, "Couldn't load glad!")
BK_CORE_INFO("Opengl Raw Version : {0}",GL_VERSION);
context = GraphicsContext::Create((void*)p_window);
context->Init();
glfwSetWindowUserPointer(p_window, &p_data);
set_vsync(true);
init_event_callbacks();
SetVsync(true);
InitEventCallbacks();
}
void WinGLFW::init_event_callbacks()
void GlfwWindow::InitEventCallbacks()
{
glfwSetFramebufferSizeCallback(p_window, [](GLFWwindow* window, int width, int height)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
GlfwWindowData& data = *(GlfwWindowData*)glfwGetWindowUserPointer(window);
WindowResizeEvent e(data.width = (uint)width, data.height = (uint)height);
data.callback(e);
});
glfwSetWindowCloseCallback(p_window, [](GLFWwindow* window)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
GlfwWindowData& data = *(GlfwWindowData*)glfwGetWindowUserPointer(window);
WindowCloseEvent e;
data.callback(e);
});
glfwSetKeyCallback(p_window, [](GLFWwindow* window, int key, int scancode, int action, int mods)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
GlfwWindowData& data = *(GlfwWindowData*)glfwGetWindowUserPointer(window);
switch(action)
{
case GLFW_PRESS:
@ -92,7 +93,7 @@ namespace Bk {
});
glfwSetMouseButtonCallback(p_window, [](GLFWwindow* window, int button, int action, int mods)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
GlfwWindowData& data = *(GlfwWindowData*)glfwGetWindowUserPointer(window);
switch(action)
{
case GLFW_PRESS:
@ -111,71 +112,48 @@ namespace Bk {
});
glfwSetScrollCallback(p_window, [](GLFWwindow* window, double offset_x, double offset_y)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
GlfwWindowData& data = *(GlfwWindowData*)glfwGetWindowUserPointer(window);
MouseScrollEvent e((float)offset_x, (float)offset_y);
data.callback(e);
});
glfwSetCursorPosCallback(p_window, [](GLFWwindow* window, double pos_x, double pos_y)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
GlfwWindowData& data = *(GlfwWindowData*)glfwGetWindowUserPointer(window);
MouseMoveEvent e((float)pos_x, (float)pos_y);
data.callback(e);
});
}
void WinGLFW::on_update()
void GlfwWindow::OnUpdate()
{
if (h_is_open)
{
glClearColor(1,0,0.5,1);
glClear(GL_COLOR_BUFFER_BIT);
glfwPollEvents();
glfwSwapBuffers(p_window);
if (p_shutdown && h_is_open) { shutdown(); }
}
float time = glfwGetTime();
dt = DeltaTime(time - lastFrameTime);
lastFrameTime = time;
glfwPollEvents();
context->SwapBuffers();
}
void WinGLFW::set_event_callback(const EventCallback callback)
void GlfwWindow::SetEventCallback(const EventCallback callback)
{
p_data.callback = callback;
}
void WinGLFW::set_vsync(bool enable)
void GlfwWindow::SetVsync(bool enable)
{
if (h_is_open)
{
if (enable) { glfwSwapInterval(1); }
else { glfwSwapInterval(0); }
p_data.vsync = enable;
}
if (enable) { glfwSwapInterval(1); }
else { glfwSwapInterval(0); }
p_data.vsync = enable;
}
bool WinGLFW::is_vsync() const
bool GlfwWindow::IsVsync() const
{
return p_data.vsync;
}
void WinGLFW::shutdown()
{
h_is_open = false;
p_shutdown = false;
glfwDestroyWindow(p_window);
}
void WinGLFW::close()
void GlfwWindow::Close()
{
p_shutdown = true;
}
void WinGLFW::open()
{
if (!h_is_open)
{
init();
}
glfwDestroyWindow(p_window);
}
}
}

@ -0,0 +1,51 @@
#pragma once
#include "bakara/core/deltatime.h"
#include "bakara/core/window.h"
#include "bakara/renderer/graphics_context.h"
struct GLFWwindow;
namespace Bk::Platform {
struct GlfwWindowData
{
std::string title;
uint width;
uint height;
bool vsync;
EventCallback callback;
};
class GlfwWindow : public Window
{
public:
GlfwWindow(const WindowProps& props);
virtual ~GlfwWindow();
inline uint GetWidth() const override { return p_data.width; }
inline uint GetHeight() const override { return p_data.height; }
void OnUpdate() override;
void SetEventCallback(const EventCallback callback) override;
void SetVsync(bool enable) override;
bool IsVsync() const override;
void Close() override;
void* GetNativeWindow() override { return p_window; }
virtual DeltaTime GetTime() override { return dt; }
private:
GLFWwindow* p_window;
GlfwWindowData p_data;
Scope<GraphicsContext> context;
float lastFrameTime = 0.0f;
DeltaTime dt = { 0.0f };
void InitEventCallbacks();
void Init();
};
}

@ -0,0 +1,56 @@
#include "opengl_buffer.h"
#include <glad/glad.h>
namespace Bk::Platform
{
OpenglVertexBuffer::OpenglVertexBuffer(float* vertices, u32 size)
{
glGenBuffers(1, &id);
glBindBuffer(GL_ARRAY_BUFFER, id);
glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW);
}
OpenglVertexBuffer::~OpenglVertexBuffer()
{
glDeleteBuffers(1, &id);
}
void OpenglVertexBuffer::Bind()
{
glBindBuffer(GL_ARRAY_BUFFER, id);
}
void OpenglVertexBuffer::Unbind()
{
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
OpenglIndexBuffer::OpenglIndexBuffer(u32* indices, u32 count)
: count(count)
{
glGenBuffers(1, &id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(u32), indices, GL_STATIC_DRAW);
}
OpenglIndexBuffer::~OpenglIndexBuffer()
{
glDeleteBuffers(1, &id);
}
void OpenglIndexBuffer::Bind()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id);
}
void OpenglIndexBuffer::Unbind()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
u32 OpenglIndexBuffer::GetCount()
{
return count;
}
}

@ -0,0 +1,35 @@
#pragma once
#include "bakara/renderer/buffer.h"
#include "bakara/renderer/buffer_layout.h"
namespace Bk::Platform
{
class OpenglVertexBuffer : public VertexBuffer
{
public:
OpenglVertexBuffer(float* vertices, u32 size);
virtual ~OpenglVertexBuffer();
virtual void Bind() override;
virtual void Unbind() override;
virtual void SetLayout(BufferLayout layout) override { this->layout = layout; }
virtual BufferLayout& GetLayout() override { return layout; }
private:
BufferLayout layout;
u32 id;
};
class OpenglIndexBuffer : public IndexBuffer
{
public:
OpenglIndexBuffer(u32* vertices, u32 count);
virtual ~OpenglIndexBuffer();
virtual void Bind() override;
virtual void Unbind() override;
virtual u32 GetCount() override;
private:
u32 id;
u32 count;
};
}

@ -0,0 +1,33 @@
#include "bakatools/logging/assert.h"
#include "bakatools/logging/log.h"
#include "opengl_context.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
namespace Bk::Platform
{
OpenglContext::OpenglContext(void* window_handle)
: window_handle((GLFWwindow*)window_handle) {}
void OpenglContext::Init()
{
glfwMakeContextCurrent(window_handle);
int success = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
BK_CORE_MSG_ASSERT(success, "Couldn't load glad!")
GLint majVers = 0, minVers = 0;
glGetIntegerv(GL_MAJOR_VERSION, &majVers);
glGetIntegerv(GL_MINOR_VERSION, &minVers);
BK_CORE_INFO("Hardware info ");
BK_CORE_INFO(" - Opengl Version {0}.{1}", majVers, minVers);
BK_CORE_INFO(" - GPU Vendor {0}", reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
BK_CORE_INFO(" - Renderer {0}", reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
BK_CORE_INFO(" - Renderer Version {0}", reinterpret_cast<const char*>(glGetString(GL_VERSION)));
BK_CORE_MSG_ASSERT(majVers > 4 || (majVers == 4 && minVers >= 2), "Bakara only support Opengl versions 4.2 or more.")
}
void OpenglContext::SwapBuffers()
{
glfwSwapBuffers(window_handle);
}
}

@ -0,0 +1,20 @@
#pragma once
#include "bakara/renderer/graphics_context.h"
struct GLFWwindow;
namespace Bk::Platform
{
class OpenglContext : public GraphicsContext
{
public:
OpenglContext(void* window_handle);
virtual ~OpenglContext() override { }
void Init() override;
void SwapBuffers() override;
private:
GLFWwindow* window_handle;
};
}

@ -0,0 +1,28 @@
#include "opengl_renderer_api.h"
#include <glad/glad.h>
namespace Bk
{
void OpenglRendererAPI::Init()
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
}
void OpenglRendererAPI::Clear(float red, float green, float blue, float alpha)
{
glClearColor(red, green, blue, alpha);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void OpenglRendererAPI::SetViewport(u32 width, u32 height)
{
glViewport(0, 0, width, height);
}
void OpenglRendererAPI::DrawIndexed(Ref<VertexArray> va)
{
glDrawElements(GL_TRIANGLES, va->GetIndexbuffer()->GetCount(), GL_UNSIGNED_INT, nullptr);
}
}

@ -0,0 +1,17 @@
#pragma once
#include "bakara/renderer/renderer_api.h"
#include "bakara/renderer/vertex_array.h"
#include "bakatools/container/types.h"
namespace Bk
{
class OpenglRendererAPI : public RendererAPI
{
public:
virtual void Init() override;
virtual void Clear(float red, float green, float blue, float alpha) override;
virtual void SetViewport(u32 width, u32 height) override;
virtual void DrawIndexed(Ref<VertexArray> va) override;
};
}

@ -0,0 +1,158 @@
#include "opengl_shader.h"
#include "bakatools/file_system/file.h"
#include "bakatools/logging/assert.h"
#include "bakara/math/types.h"
#include "bakatools/logging/log.h"
#include <unordered_map>
namespace Bk::Platform
{
static GLenum ShaderTypeFromString(std::string type)
{
if (type == "vertex") return GL_VERTEX_SHADER;
else if (type == "fragment" || type == "pixel") return GL_FRAGMENT_SHADER;
BK_CORE_MSG_ASSERT(false, "An known shader type")
return 0;
}
OpenglShader::OpenglShader(const std::string& filePath)
{
File file = File(filePath);
BK_CORE_MSG_ASSERT(file.exists(), "Shader file not found")
std::string filename = file.name();
size_t pos = filename.find_last_of(".");
name = pos == std::string::npos ? filename : filename.substr(0, pos);
std::string source = file.read();
auto sources = PreProcess(source);
Compile(sources);
}
OpenglShader::OpenglShader(const std::string& name, const std::string& vertexSrc, const std::string& fragSrc)
: name(name)
{
Compile({
{ GL_VERTEX_SHADER, vertexSrc },
{ GL_FRAGMENT_SHADER, fragSrc }
});
}
std::unordered_map<GLenum, std::string> OpenglShader::PreProcess(std::string source)
{
std::unordered_map<GLenum, std::string> sources;
const std::string token("#type");
size_t pos = source.find(token, 0);
BK_CORE_MSG_ASSERT(pos != std::string::npos, "Not shader found in file")
while (pos != std::string::npos)
{
size_t eol = source.find_first_of("\n", pos);
BK_CORE_MSG_ASSERT(eol != std::string::npos, "Syntax Error in shader file");
size_t begin = pos + token.length() + 1;
std::string type = source.substr(begin, eol - begin);
GLenum glType = ShaderTypeFromString(type);
size_t nextLine = source.find_first_not_of("\n", eol);
pos = source.find(token, nextLine);
sources[glType] = (pos == std::string::npos) ? source.substr(nextLine) : source.substr(nextLine, pos - nextLine);
}
return sources;
}
void OpenglShader::Compile(std::unordered_map<GLenum, std::string> sources)
{
std::vector<GLuint> shaders;
id = glCreateProgram();
for(auto& kv : sources)
{
GLenum type = kv.first;
const GLchar* shaderSrc = kv.second.c_str();
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &shaderSrc, NULL);
glCompileShader(shader);
int info;
glGetShaderiv(shader, GL_COMPILE_STATUS, &info);
if(!info) {
std::vector<char> infoLog;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info);
infoLog.resize(info);
glGetShaderInfoLog(shader, infoLog.size(), NULL, infoLog.data());
BK_CORE_ERROR("Shader Error : {0}", std::string(infoLog.data(),infoLog.size()));
BK_MSG_ASSERT(false, "Error with shader compilation")
}
glAttachShader(id, shader);
shaders.push_back(shader);
}
glLinkProgram(id);
int info;
glGetProgramiv(id, GL_LINK_STATUS, &info);
if(!info) {
std::vector<char> infoLog;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &info);
infoLog.resize(info);
glGetProgramInfoLog(id, infoLog.size(), NULL, infoLog.data());
BK_CORE_ERROR("Shader Error : {0}", std::string(infoLog.data(),infoLog.size()));
BK_MSG_ASSERT(false, "Error when link sharder in a program")
}
for(auto shader : shaders) glDeleteShader(shader);
}
OpenglShader::~OpenglShader()
{
glDeleteProgram(id);
}
void OpenglShader::Bind()
{
glUseProgram(id);
}
void OpenglShader::Unbind()
{
glUseProgram(0);
}
void OpenglShader::Set(const std::string name, int val)
{
glUniform1i(glGetUniformLocation(id, name.c_str()), val);
}
void OpenglShader::Set(const std::string name, bool value)
{
glUniform1i(glGetUniformLocation(id, name.c_str()), (int)value);
}
void OpenglShader::Set(const std::string name, float val)
{
glUniform1f(glGetUniformLocation(this->id, name.c_str()), val);
}
void OpenglShader::Set(const std::string name, float v1, float v2, float v3)
{
glUniform3f(glGetUniformLocation(id, name.c_str()), v1, v2, v3);
}
void OpenglShader::Set(const std::string name, Vec3 v)
{
this->Set(name, v.x, v.y, v.z);
}
void OpenglShader::Set(const std::string name, float v1, float v2, float v3, float v4)
{
glUniform4f(glGetUniformLocation(id, name.c_str()), v1, v2, v3, v4);
}
void OpenglShader::Set(const std::string name, Vec4 v)
{
this->Set(name, v.x, v.y, v.z, v.w);
}
void OpenglShader::Set(const std::string name, Mat3 val)
{
glUniformMatrix3fv(glGetUniformLocation(this->id, name.c_str()), 1, GL_FALSE, glm::value_ptr(val));
}
void OpenglShader::Set(const std::string name, Mat4 val)
{
glUniformMatrix4fv(glGetUniformLocation(this->id, name.c_str()), 1, GL_FALSE, glm::value_ptr(val));
}
}

@ -0,0 +1,38 @@
#pragma once
#include "bakara/renderer/shader.h"
#include <glad/glad.h>
#include <string>
#include <unordered_map>
namespace Bk::Platform
{
class OpenglShader : public Shader
{
public:
OpenglShader(const std::string& filePath);
OpenglShader(const std::string& name, const std::string& vertexSrc, const std::string& fragSrc);
virtual ~OpenglShader();
virtual const std::string& GetName() override { return name; }
virtual void Bind() override;
virtual void Unbind() override;
virtual void Set(const std::string name, int val) override;
virtual void Set(const std::string name, bool val) override;
virtual void Set(const std::string name, float val) override;
virtual void Set(const std::string name, float v1, float v2, float v3) override;
virtual void Set(const std::string name, Vec3 v) override;
virtual void Set(const std::string name, float v1, float v2, float v3, float v4) override;
virtual void Set(const std::string name, Vec4 v) override;
virtual void Set(const std::string name, Mat3 val) override;
virtual void Set(const std::string name, Mat4 val) override;
private:
unsigned int id;
std::string name;
std::unordered_map<GLenum, std::string> PreProcess(std::string source);
void Compile(std::unordered_map<GLenum, std::string> sources);
};
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save