Major changes

- Major maintenance
This commit is contained in:
Light 2021-07-29 17:12:13 +04:30
parent ec8669d3fe
commit 9033ceffa1
104 changed files with 1084 additions and 867 deletions

View file

@ -1,160 +0,0 @@
#pragma once
#include <memory>
namespace Light {
// Ref (Ref)
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T, typename... Args>
constexpr Ref<T> CreateRef(Args&&... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
template<typename T>
constexpr Ref<T> MakeRef(T* rawPointer)
{
return std::shared_ptr<T>(rawPointer);
}
// Scope (std::unique_ptr)
template<typename T>
using Scope = std::unique_ptr<T>;
template<typename T, typename... Args>
constexpr std::unique_ptr<T> CreateScope(Args&&... args)
{
return std::make_unique<T>(std::forward<Args>(args)...);
}
template<typename T>
constexpr std::unique_ptr<T> MakeScope(T* rawPointer)
{
return std::unique_ptr<T>(rawPointer);
}
}
// platform
#define LT_WIN(x) // windows
#define LT_LIN(x) // linux
#define LT_MAC(x) // mac
#if defined(LIGHT_PLATFORM_WINDOWS)
#define LT_BUILD_PLATFORM "Windows"
#define LT_WIN(x) x
#elif defined(LIGHT_PLATFORM_LINUX)
#define LT_BUILD_PLATFORM "Linux"
#define LT_LIN(x) x
#elif defined(LIGHT_PLATFORM_MAC)
#error "Unsupported platform: MAC"
#define LT_MAC(x) x
#else
#error "Unsupported platform: Unknown"
#endif
// operations
#define BIT(x) 1 << x
// assertions
#if defined(LIGHT_DIST)
#define LT_ENGINE_ASSERT(x, ...) { if(!(x)) { LT_FILE_CRITICAL(__VA_ARGS__); throw ::Light::FailedEngineAssertion(__FILE__, __LINE__); } }
#define LT_CLIENT_ASSERT(x, ...) { if(!(x)) { LT_FILE_CRITICAL(__VA_ARGS__); throw ::Light::FailedClientAssertion(__FILE__, __LINE__); } }
#else
#define LT_ENGINE_ASSERT(x, ...) { if(!(x)) { LT_ENGINE_CRITICAL(__VA_ARGS__); LT_BREAK(); throw ::Light::FailedEngineAssertion(__FILE__, __LINE__); } }
#define LT_CLIENT_ASSERT(x, ...) { if(!(x)) { LT_CLIENT_CRITICAL(__VA_ARGS__); LT_BREAK(); throw ::Light::FailedClientAssertion(__FILE__, __LINE__); } }
#endif
///*** [ PORTABLES ] ***///
//** PORTABLE_DEBUG_BREAK **//
// copied from: https://github.com/nemequ/portable-snippets/tree/master/debug-trap
#if defined(__has_builtin) && !defined(__ibmxl__)
#if __has_builtin(__builtin_debugtrap)
#define LT_BREAK() __builtin_debugtrap()
#elif __has_builtin(__debugbreak)
#define LT_BREAK() __debugbreak()
#endif
#endif
#if !defined(LT_BREAK)
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
#define LT_BREAK() __debugbreak()
#elif defined(__ARMCC_VERSION)
#define LT_BREAK() __breakpoint(42)
#elif defined(__ibmxl__) || defined(__xlC__)
#include <builtins.h>
#define LT_BREAK() __trap(42)
#elif defined(__DMC__) && defined(_M_IX86)
static inline void LT_BREAK(void) { __asm int 3h; }
#elif defined(__i386__) || defined(__x86_64__)
static inline void LT_BREAK(void) { __asm__ __volatile__("int3"); }
#elif defined(__thumb__)
static inline void LT_BREAK(void) { __asm__ __volatile__(".inst 0xde01"); }
#elif defined(__aarch64__)
static inline void LT_BREAK(void) { __asm__ __volatile__(".inst 0xd4200000"); }
#elif defined(__arm__)
static inline void LT_BREAK(void) { __asm__ __volatile__(".inst 0xe7f001f0"); }
#elif defined (__alpha__) && !defined(__osf__)
static inline void LT_BREAK(void) { __asm__ __volatile__("bpt"); }
#elif defined(_54_)
static inline void LT_BREAK(void) { __asm__ __volatile__("ESTOP"); }
#elif defined(_55_)
static inline void LT_BREAK(void) { __asm__ __volatile__(";\n .if (.MNEMONIC)\n ESTOP_1\n .else\n ESTOP_1()\n .endif\n NOP"); }
#elif defined(_64P_)
static inline void LT_BREAK(void) { __asm__ __volatile__("SWBP 0"); }
#elif defined(_6x_)
static inline void LT_BREAK(void) { __asm__ __volatile__("NOP\n .word 0x10000000"); }
#elif defined(__STDC_HOSTED__) && (__STDC_HOSTED__ == 0) && defined(__GNUC__)
#define LT_BREAK() __builtin_trap()
#else
#include <signal.h>
#if defined(SIGTRAP)
#define LT_BREAK() raise(SIGTRAP)
#else
#define LT_BREAK() raise(SIGABRT)
#endif
#endif
#endif
#if !defined(LT_BREAK)
#define LT_BERAK LT_ENGINE_WARN("Unable to break!, LT_BREAK macro is undefined")
#endif
//** PORTABLE_DEBUG_BREAK **//
///*** [ PORTABLES ] ***///
#ifndef LT_LOGGER_H
#include "Debug/Logger.h"
#define LT_LOGGER_H
#endif
#include "Debug/Exceptions.h"
#include "Utility/Stringifier.h"

View file

@ -0,0 +1,91 @@
#pragma once
#include <memory>
namespace Light {
// Ref (Ref)
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T, typename... Args>
constexpr Ref<T> CreateRef(Args&&... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
template<typename T>
constexpr Ref<T> MakeRef(T* rawPointer)
{
return std::shared_ptr<T>(rawPointer);
}
// Scope (std::unique_ptr)
template<typename T>
using Scope = std::unique_ptr<T>;
template<typename T, typename... Args>
constexpr std::unique_ptr<T> CreateScope(Args&&... args)
{
return std::make_unique<T>(std::forward<Args>(args)...);
}
template<typename T>
constexpr std::unique_ptr<T> MakeScope(T* rawPointer)
{
return std::unique_ptr<T>(rawPointer);
}
}
//========== PLATFORM ==========//
#define LT_WIN(x) // windows
#define LT_LIN(x) // linux
#define LT_MAC(x) // mac
#if defined(LIGHT_PLATFORM_WINDOWS)
#define LT_BUILD_PLATFORM "Windows"
#define LT_WIN(x) x
#elif defined(LIGHT_PLATFORM_LINUX)
#define LT_BUILD_PLATFORM "Linux"
#define LT_LIN(x) x
#elif defined(LIGHT_PLATFORM_MAC)
#error "Unsupported platform: MAC"
#define LT_MAC(x) x
#else
#error "Unsupported platform: Unknown"
#endif
//========== PLATFORM ==========//
//====================================================================== OPERATIONS ======================================================================//
/* assertions */
#define LT_ENGINE_ASSERT(x, ...) { if(!(x)) { LT_ENGINE_CRITICAL(__VA_ARGS__); LT_DEBUG_TRAP(); throw ::Light::FailedEngineAssertion(__FILE__, __LINE__); } }
#define LT_CLIENT_ASSERT(x, ...) { if(!(x)) { LT_CLIENT_CRITICAL(__VA_ARGS__); LT_DEBUG_TRAP(); throw ::Light::FailedClientAssertion(__FILE__, __LINE__); } }
/* bit-wise */
#define BIT(x) 1 << x
/* token */
#define LT_PAIR_TOKEN_VALUE_TO_NAME(token) { token, #token }
#define LT_PAIR_TOKEN_NAME_TO_VALUE(token) { #token, token }
#define LT_TOKEN_NAME(token) #token
//====================================================================== OPERATIONS ======================================================================//
//========== ESSENTIAL_HEADERS ==========//
/* debug */
#ifndef LT_LOGGER_H
#include "Debug/Logger.h"
#define LT_LOGGER_H
#endif
#include "Debug/Exceptions.h"
/* portables */
#include "Base/Portables/DebugTrap.h"
/* utility */
#include "Utility/Stringifier.h"
//========== ESSENTIAL_HEADERS ==========//

View file

@ -20,21 +20,25 @@ int main(int argc, char** argv)
application->GameLoop();
}
// failed engine assertion
catch (Light::FailedEngineAssertion)
{
LT_ENGINE_CRITICAL("main: exitting due to unhandled 'FailedEngineAssertion'");
exitCode = -1;
}
// failed client assertion
catch (Light::FailedClientAssertion)
{
LT_ENGINE_CRITICAL("main: exitting due to unhandled 'FailedClientAssertion'");
exitCode = -2;
}
// gl exception
catch(Light::glException)
{
LT_ENGINE_CRITICAL("main: exitting due to unhandled 'glException'");
exitCode = -3;
}
// dx exception
catch (Light::dxException)
{
LT_ENGINE_CRITICAL("main: exitting due to unhandled 'dxException'");
@ -65,17 +69,20 @@ int main(int argc, char* argv[])
application->GameLoop();
}
// failed engine assertion
catch (Light::FailedEngineAssertion)
{
LT_ENGINE_CRITICAL("main: exitting due to unhandled 'FailedEngineAssertion'");
exitCode = -1;
}
// failed client assertion
catch (Light::FailedClientAssertion)
{
LT_ENGINE_CRITICAL("main: exitting due to unhandled 'FailedClientAssertion'");
exitCode = -2;
}
catch(Light::glException)
// gl exception
catch (Light::glException)
{
LT_ENGINE_CRITICAL("main: exitting due to unhandled 'glException'");
exitCode = -3;

View file

@ -0,0 +1,103 @@
#pragma once
// https://github.com/nemequ/portable-snippets/tree/master/debug-trap
#ifdef LIGHT_DIST
#ifdef _MSC_VER
#define LT_DEBUG_TRAP() LT_FILE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", __FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__
#else
#define LT_DEBUG_TRAP() LT_FILE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}", __PRETTY_FUNCTION__ )
#endif
#endif
#if !defined(LT_DEBUG_TRAP) && defined(__has_builtin) && !defined(__ibmxl__)
#if __has_builtin(__builtin_debugtrap)
#define LT_DEBUG_TRAP() __builtin_debugtrap()
#elif __has_builtin(__debugbreak)
#define LT_DEBUG_TRAP() __debugbreak()
#endif
#endif
#if !defined(LT_DEBUG_TRAP)
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
#define LT_DEBUG_TRAP() __debugbreak()
#elif defined(__ARMCC_VERSION)
#define LT_DEBUG_TRAP() __breakpoint(42)
#elif defined(__ibmxl__) || defined(__xlC__)
#include <builtins.h>
#define LT_DEBUG_TRAP() __trap(42)
#elif defined(__DMC__) && defined(_M_IX86)
static inline void LT_DEBUG_TRAP(void) { __asm int 3h; }
#elif defined(__i386__) || defined(__x86_64__)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__("int3"); }
#elif defined(__thumb__)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__(".inst 0xde01"); }
#elif defined(__aarch64__)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__(".inst 0xd4200000"); }
#elif defined(__arm__)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__(".inst 0xe7f001f0"); }
#elif defined (__alpha__) && !defined(__osf__)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__("bpt"); }
#elif defined(_54_)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__("ESTOP"); }
#elif defined(_55_)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__(";\n .if (.MNEMONIC)\n ESTOP_1\n .else\n ESTOP_1()\n .endif\n NOP"); }
#elif defined(_64P_)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__("SWBP 0"); }
#elif defined(_6x_)
static inline void LT_DEBUG_TRAP(void) { __asm__ __volatile__("NOP\n .word 0x10000000"); }
#elif defined(__STDC_HOSTED__) && (__STDC_HOSTED__ == 0) && defined(__GNUC__)
#define LT_DEBUG_TRAP() __builtin_trap()
#else
#include <signal.h>
#if defined(SIGTRAP)
#define LT_DEBUG_TRAP() raise(SIGTRAP)
#else
#define LT_DEBUG_TRAP() raise(SIGABRT)
#endif
#endif
#endif
#if !defined(LT_DEBUG_TRAP)
#define LT_BERAK LT_ENGINE_ERROR("Unable to break!, LT_BREAK macro is undefined")
#if !defined(LIGHT_IGNORE_UNDEFINED_DEBUG_BREAK)
#error "failed to define LT_BREAK, define LIGHT_IGNORE_UNDEFINED_DEBUG_BREAK to disable this error"
#elif !defined(LIGHT_DIST)
#ifdef _MSC_VER
#define LT_DEBUG_TRAP() LT_FILE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", __FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__
#else
#define LT_DEBUG_TRAP() LT_FILE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}", __PRETTY_FUNCTION__ )
#endif
#else
#ifdef _MSC_VER
#define LT_DEBUG_TRAP() LT_ENGINE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}, FILE: {}, LINE: {}", __FUNCSIG__, __FILE__, __LINE__) // or __FUNCSIG__
#else
#define LT_DEBUG_TRAP() LT_ENGINE_CRITICAL("DEBUG_TRAP REQUESTED AT: {}", __PRETTY_FUNCTION__ )
#endif
#endif
#endif

View file

@ -7,7 +7,11 @@
namespace Light {
Camera::Camera(const glm::vec2& position, float aspectRatio, float zoomLevel, const glm::vec4& clearColor /* = glm::vec4(0.1f, 0.3f, 0.7f, 1.0f) */)
: m_Up(0.0f, 1.0f, 0.0f), m_Position(position), m_AspectRatio(aspectRatio), m_ZoomLevel(zoomLevel), m_ClearColor(clearColor)
: m_Up(0.0f, 1.0f, 0.0f),
m_Position(position),
m_AspectRatio(aspectRatio),
m_ZoomLevel(zoomLevel),
m_ClearColor(clearColor)
{
}

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <glm/glm.hpp>

View file

@ -20,13 +20,19 @@
namespace Light {
Application::Application()
: m_Instrumentor(nullptr),
m_LayerStack(nullptr),
m_Input(nullptr),
m_Window(nullptr)
{
Logger::Initialize();
m_Logger = Logger::Create();
m_Instrumentor = Instrumentor::Create();
m_Instrumentor->BeginSession("Logs/ProfileResults_Startup.json");
m_LayerStack = LayerStack::Create();
m_Input = Input::Create();
m_Instrumentor->BeginSession("Logs/ProfileResults_Startup.json");
m_Window = Window::Create(std::bind(&Application::OnEvent, this, std::placeholders::_1));
}
@ -43,7 +49,7 @@ namespace Light {
// log debug data
LogDebugData();
Logger::LogDebugData();
m_Logger->LogDebugData();
m_Window->GetGfxContext()->LogDebugData();
m_Window->GetGfxContext()->GetUserInterface()->LogDebugData();
@ -53,7 +59,7 @@ namespace Light {
m_Instrumentor->EndSession(); // ProfileResults_GameLoop //
m_Instrumentor->BeginSession("Logs/ProfileResults_GameLoop.json");
//** GAMELOOP **//
/* game loop */
DeltaTimer deltaTimer;
while (!m_Window->IsClosed())
{
@ -116,9 +122,9 @@ namespace Light {
if (event.HasCategory(InputEventCategory))
m_Input->OnEvent(event);
// layers
/* layers */
// return if the event is an input event and 'Input' has disabled the game events
if (event.HasCategory(InputEventCategory) && !m_Input->IsReceivingGameEvents())
if (event.HasCategory(InputEventCategory) && !m_Input->IsReceivingGameEvents())
return;
for (auto it = m_LayerStack->rbegin(); it != m_LayerStack->rend(); it++)

View file

@ -1,13 +1,13 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include "Debug/Instrumentor.h"
#include "Layer/LayerStack.h"
#include "Input/Input.h"
#include "Layer/LayerStack.h"
namespace Light {
class Window;
@ -18,12 +18,13 @@ namespace Light {
class Application
{
private:
Scope<Instrumentor> m_Instrumentor = nullptr;
Scope<Logger> m_Logger;
Scope<Instrumentor> m_Instrumentor;
Scope<LayerStack> m_LayerStack;
Scope<Input> m_Input;
protected:
Scope<Window> m_Window = nullptr;
Scope<Window> m_Window;
public:
Application(const Application&) = delete;

View file

@ -1,12 +1,13 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
namespace Light {
class Event;
class GraphicsContext;
struct WindowProperties
@ -20,21 +21,29 @@ namespace Light {
{
protected:
Scope<GraphicsContext> m_GraphicsContext;
WindowProperties m_Properties = {};
bool b_Closed = false;
WindowProperties m_Properties;
bool b_Closed;
public:
static Scope<Window> Create(std::function<void(Event&)> callback);
Window()
: m_GraphicsContext(nullptr),
m_Properties{},
b_Closed(false)
{
}
Window(const Window&) = delete;
Window& operator=(const Window&) = delete;
virtual ~Window() = default;
/* events */
virtual void PollEvents() = 0;
virtual void OnEvent(const Event& event) = 0;
//* SETTERS *//
//======================================== SETTERS ========================================//
virtual void SetProperties(const WindowProperties& properties, bool affectVisibility = false) = 0;
virtual void SetTitle(const std::string& title) = 0;
@ -44,8 +53,9 @@ namespace Light {
inline void Close() { b_Closed = true; }
virtual void SetVSync(bool vsync, bool toggle = false) = 0;
virtual void SetVisibility(bool visible, bool toggle = false) = 0;
//======================================== SETTERS ========================================//
//* GETTERS *//
//============================== GETTERS ==============================//
inline GraphicsContext* GetGfxContext() const { return m_GraphicsContext.get(); }
inline const WindowProperties& GetProperties() const { return m_Properties; }
@ -57,9 +67,9 @@ namespace Light {
inline bool IsClosed() const { return b_Closed; }
inline bool IsVSync() const { return m_Properties.vsync; }
inline bool IsVisible() const { return m_Properties.visible; }
//============================== GETTERS ==============================//
protected:
Window() = default;
};
}

View file

@ -1,10 +1,9 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <ostream>
#include <fstream>
#include <ostream>
#include <chrono>
namespace Light {

View file

@ -6,14 +6,22 @@
namespace Light {
Ref<spdlog::logger> Logger::s_EngineLogger = nullptr;
Ref<spdlog::logger> Logger::s_ClientLogger = nullptr;
Ref<spdlog::logger> Logger::s_FileLogger = nullptr;
Logger* Logger::s_Context = nullptr;
std::string Logger::s_LogFilePath = LT_LOG_FILE_LOCATION;
void Light::Logger::Initialize()
Scope<Logger> Logger::Create()
{
return MakeScope<Logger>(new Logger());
}
Logger::Logger()
: m_EngineLogger(nullptr),
m_ClientLogger(nullptr),
m_FileLogger(nullptr),
m_LogFilePath(LT_LOG_FILE_LOCATION)
{
LT_ENGINE_ASSERT(!s_Context, "Logger::Logger: an instance of 'Logger' already exists, do not construct this class!");
s_Context = this;
// set spdlog pattern
#if defined(LIGHT_PLATFORM_WINDOWS)
spdlog::set_pattern("%^[%M:%S:%e] <%n>: %v%$");
@ -22,16 +30,16 @@ namespace Light {
#endif
// create loggers
#ifndef LIGHT_DIST
s_EngineLogger = spdlog::stdout_color_mt("Engine");
s_ClientLogger = spdlog::stdout_color_mt("Client");
m_EngineLogger = spdlog::stdout_color_mt("Engine");
m_ClientLogger = spdlog::stdout_color_mt("Client");
#endif
s_FileLogger = spdlog::basic_logger_mt("File", s_LogFilePath);
s_FileLogger->set_pattern("%^[%M:%S:%e] <%l>: %v%$");
m_FileLogger = spdlog::basic_logger_mt("File", m_LogFilePath);
m_FileLogger->set_pattern("%^[%M:%S:%e] <%l>: %v%$");
// set level
#if defined(LIGHT_DEBUG)
s_EngineLogger->set_level(spdlog::level::trace);
s_ClientLogger->set_level(spdlog::level::trace);
m_EngineLogger->set_level(spdlog::level::trace);
m_ClientLogger->set_level(spdlog::level::trace);
#elif defined (LIGHT_RELEASE)
s_EngineLogger->set_level(spdlog::level::info);
s_ClientLogger->set_level(spdlog::level::info);
@ -43,9 +51,9 @@ namespace Light {
// #todo: improve
LT_ENGINE_INFO("________________________________________");
LT_ENGINE_INFO("Logger::");
LT_ENGINE_INFO(" ClientLevel : {}", Stringifier::spdlogLevel(s_ClientLogger->level()));
LT_ENGINE_INFO(" EngineLevel : {}", Stringifier::spdlogLevel(s_EngineLogger->level()));
LT_ENGINE_INFO(" FileLevel : {}", Stringifier::spdlogLevel(s_FileLogger->level()));
LT_ENGINE_INFO(" ClientLevel : {}", Stringifier::spdlogLevel(m_ClientLogger->level()));
LT_ENGINE_INFO(" EngineLevel : {}", Stringifier::spdlogLevel(m_EngineLogger->level()));
LT_ENGINE_INFO(" FileLevel : {}", Stringifier::spdlogLevel(m_FileLogger->level()));
LT_ENGINE_INFO(" DefaultLevel: {}", Stringifier::spdlogLevel(spdlog::get_level()));
LT_ENGINE_INFO("________________________________________");
}

View file

@ -1,13 +1,13 @@
#pragma once
#define LT_LOGGER_H
#include "Base.h"
#include "Base/Base.h"
#include <spdlog/spdlog.h>
// LOGGER MACROS //
#define LT_LOG_FILE_LOCATION "Logs/Logger.txt";
#define LT_LOG_FILE_LOCATION "Logs/Logger.txt"
// File
#define LT_FILE_INFO(...) ::Light::Logger::GetFileLogger()->log(spdlog::level::info , __VA_ARGS__)
@ -48,19 +48,22 @@ namespace Light {
class Logger
{
private:
static Ref<spdlog::logger> s_EngineLogger, s_ClientLogger, s_FileLogger;
static std::string s_LogFilePath;
static Logger* s_Context;
Ref<spdlog::logger> m_EngineLogger, m_ClientLogger, m_FileLogger;
std::string m_LogFilePath;
public:
Logger() = delete;
static Scope<Logger> Create();
static void Initialize();
static inline Ref<spdlog::logger> GetEngineLogger() { return s_Context->m_EngineLogger; }
static inline Ref<spdlog::logger> GetClientLogger() { return s_Context->m_ClientLogger; }
static inline Ref<spdlog::logger> GetFileLogger() { return s_Context->m_FileLogger; }
static inline Ref<spdlog::logger> GetEngineLogger() { return s_EngineLogger; }
static inline Ref<spdlog::logger> GetClientLogger() { return s_ClientLogger; }
static inline Ref<spdlog::logger> GetFileLogger() { return s_FileLogger; }
void LogDebugData();
static void LogDebugData();
private:
Logger();
};
}

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Event.h"
#include "Base/Base.h"
#include <sstream>
namespace Light {
@ -13,7 +14,10 @@ namespace Light {
const int m_Key;
public:
KeyPressedEvent(int key): m_Key(key) { }
KeyPressedEvent(int key)
: m_Key(key)
{
}
inline int GetKey() const { return m_Key; }
@ -33,7 +37,10 @@ namespace Light {
const int m_Key;
public:
KeyReleasedEvent(int key): m_Key(key) { }
KeyReleasedEvent(int key)
: m_Key(key)
{
}
inline int GetKey() const { return m_Key; }

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Event.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
#include <sstream>
@ -15,7 +16,10 @@ namespace Light {
const glm::vec2 m_Position;
public:
MouseMovedEvent(float x, float y) : m_Position(x, y) { }
MouseMovedEvent(float x, float y)
: m_Position(x, y)
{
}
inline const glm::vec2& GetPosition() const { return m_Position; }
@ -38,7 +42,10 @@ namespace Light {
const float m_Offset;
public:
WheelScrolledEvent(float offset) : m_Offset(offset) { }
WheelScrolledEvent(float offset)
: m_Offset(offset)
{
}
inline float GetOffset() const { return m_Offset; }
@ -58,7 +65,10 @@ namespace Light {
const int m_Button;
public:
ButtonPressedEvent(int button): m_Button(button) { }
ButtonPressedEvent(int button)
: m_Button(button)
{
}
inline int GetButton() const { return m_Button; }
@ -78,7 +88,10 @@ namespace Light {
const int m_Button;
public:
ButtonReleasedEvent(int button) : m_Button(button) { }
ButtonReleasedEvent(int button)
: m_Button(button)
{
}
inline int GetButton() const { return m_Button; }
@ -88,7 +101,6 @@ namespace Light {
ss << "ButtonReleased: " << m_Button;
return ss.str();
}
EVENT_TYPE(ButtonReleased)
EVENT_CATEGORY(InputEventCategory | MouseEventCategory)
};

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Event.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
#include <sstream>
@ -26,7 +27,10 @@ namespace Light {
const glm::ivec2 m_Position;
public:
WindowMovedEvent(int x, int y): m_Position(x, y) { }
WindowMovedEvent(int x, int y)
: m_Position(x, y)
{
}
const glm::ivec2& GetPosition() const{ return m_Position; }
@ -46,7 +50,10 @@ namespace Light {
const glm::uvec2 m_Size;
public:
WindowResizedEvent(unsigned int width, unsigned int height): m_Size(width, height) { }
WindowResizedEvent(unsigned int width, unsigned int height)
: m_Size(width, height)
{
}
const glm::uvec2& GetSize() const { return m_Size; }

View file

@ -9,7 +9,6 @@
#include "GraphicsContext.h"
namespace Light {
Scope<Blender> Blender::Create(Ref<SharedContext> sharedContext)

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {
@ -35,8 +35,6 @@ namespace Light {
class Blender
{
private:
public:
static Scope<Blender> Create(Ref<SharedContext> sharedContext);

View file

@ -13,7 +13,7 @@
namespace Light {
//* CONSTANT_BUFFER *//
//================================================== CONSTANT_BUFFER ==================================================//
Scope<ConstantBuffer> ConstantBuffer::Create(ConstantBufferIndex index, unsigned int size, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
@ -29,8 +29,9 @@ namespace Light {
return nullptr;
}
}
//================================================== CONSTANT_BUFFER ==================================================//
//* VERTEX_BUFFER *//
//================================================== VERTEX_BUFFER ==================================================//
Ref<VertexBuffer> VertexBuffer::Create(float* vertices, unsigned int stride, unsigned int count, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
@ -46,8 +47,9 @@ namespace Light {
return nullptr;
}
}
//================================================== VERTEX_BUFFER ==================================================//
//* INDEX_BUFFER *//
//======================================== INDEX_BUFFER ========================================//
Ref<IndexBuffer> IndexBuffer::Create(unsigned int* indices, unsigned int count, Ref<SharedContext> sharedContext)
{
switch (GraphicsContext::GetGraphicsAPI())
@ -63,5 +65,6 @@ namespace Light {
return nullptr;
}
}
//======================================== INDEX_BUFFER ========================================//
}

View file

@ -1,32 +1,32 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {
class SharedContext;
enum ConstantBufferIndex
enum class ConstantBufferIndex
{
ViewProjection = 0u
};
//* CONSTANT_BUFFER *//
//========== CONSTANT_BUFFER ==========//
class ConstantBuffer
{
public:
static Scope<ConstantBuffer> Create(ConstantBufferIndex index, unsigned int size, Ref<SharedContext> sharedContext);
virtual void Bind() = 0;
virtual void* Map() = 0;
virtual void UnMap() = 0;
virtual void Bind() = 0;
protected:
ConstantBuffer() = default;
};
//* VERTEX_BUFFER *//
//========== VERTEX_BUFFER ==========//
class VertexBuffer
{
public:
@ -44,7 +44,7 @@ namespace Light {
VertexBuffer() = default;
};
//* INDEX_BUFFER *//
//========== INDEX_BUFFER ==========//
class IndexBuffer
{
public:

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
@ -14,8 +14,6 @@ namespace Light {
unsigned int samples = 1;
glm::uvec4 defaultColor = glm::uvec4(0u);
bool swapChainTarget = false; // render to the screen
};
class Framebuffer
@ -23,12 +21,12 @@ namespace Light {
public:
static Ref<Framebuffer> Create(const FramebufferSpecification& specification, Ref<SharedContext> sharedContext);
virtual void* GetColorAttachment() = 0;
virtual void BindAsTarget() = 0;
virtual void BindAsResource() = 0;
virtual void Resize(const glm::vec2& size) = 0;
virtual void Resize(const glm::uvec2& size) = 0;
virtual void* GetColorAttachment() = 0;
protected:
Framebuffer() = default;

View file

@ -7,17 +7,22 @@
#include "DirectX/dxSharedContext.h"
#endif
// forward declaration
#include "Graphics/Renderer.h"
#include "Graphics/RenderCommand.h"
#include "UserInterface/UserInterface.h"
#include "Utility/ResourceManager.h"
#include "Blender.h" // required for forward declaration
#include "Buffers.h" // required for forward declaration
#include "Renderer.h" // required for forward declaration
#include "RenderCommand.h" // required for forward declaration
#include "UserInterface/UserInterface.h" // required for forward declaration
#include "Utility/ResourceManager.h" // required for forward declaration
namespace Light {
GraphicsContext* GraphicsContext::s_Context = nullptr;
GraphicsContext::~GraphicsContext() {}
GraphicsContext::~GraphicsContext()
{
}
Scope<GraphicsContext> GraphicsContext::Create(GraphicsAPI api, GLFWwindow* windowHandle)
{
@ -46,11 +51,12 @@ namespace Light {
Scope<GraphicsContext> scopeGfx;
switch (api)
{
// opengl
case GraphicsAPI::OpenGL:
scopeGfx = CreateScope<glGraphicsContext>(windowHandle);
s_Context = scopeGfx.get();
break;
// directx
case GraphicsAPI::DirectX: LT_WIN(
scopeGfx = CreateScope<dxGraphicsContext>(windowHandle);
s_Context = scopeGfx.get();

View file

@ -1,17 +1,18 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
struct GLFWwindow;
namespace Light {
class ResourceManager;
class UserInterface;
class Renderer;
class ResourceManager;
class SharedContext;
class UserInterface;
class WindowResizedEvent;
enum class GraphicsAPI

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <glm/glm.hpp>

View file

@ -3,14 +3,14 @@
#include "Blender.h"
#include "Buffers.h"
#include "Texture.h"
#include "RenderCommand.h"
#include "Framebuffer.h"
#include "Events/WindowEvents.h"
#include "RenderCommand.h"
#include "Texture.h"
#include "Camera/Camera.h"
#include "Events/WindowEvents.h"
#include <glm/glm.hpp>
#include <glm/matrix.hpp>
#include <glm/gtc/matrix_transform.hpp>
@ -21,17 +21,20 @@ namespace Light {
Renderer::Renderer(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext)
: m_QuadRenderer(LT_MAX_QUAD_RENDERER_VERTICES, sharedContext),
m_TextureRenderer(LT_MAX_TEXTURE_RENDERER_VERTICES, sharedContext)
m_TextureRenderer(LT_MAX_TEXTURE_RENDERER_VERTICES, sharedContext),
m_ViewProjectionBuffer(nullptr),
m_RenderCommand(nullptr),
m_Blender(nullptr),
m_Camera(nullptr),
m_TargetFramebuffer(nullptr)
{
LT_ENGINE_ASSERT(!s_Context, "Renderer::Renderer: an instance of 'Renderer' already exists, do not construct this class!");
s_Context = this;
m_RenderCommand = RenderCommand::Create(windowHandle, sharedContext);
m_ViewProjectionBuffer = ConstantBuffer::Create(ConstantBufferIndex::ViewProjection, sizeof(glm::mat4), sharedContext);
m_RenderCommand = RenderCommand::Create(windowHandle, sharedContext);
m_Blender = Blender::Create(sharedContext);
m_Blender->Enable(BlendFactor::SRC_ALPHA, BlendFactor::INVERSE_SRC_ALPHA);
}
Scope<Renderer> Renderer::Create(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext)
@ -44,6 +47,7 @@ namespace Light {
m_RenderCommand->SetViewport(0u, 0u, event.GetSize().x, event.GetSize().y);
}
//======================================== DRAW_QUAD_TINT ========================================//
void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint)
{
// locals
@ -54,19 +58,19 @@ namespace Light {
const float xMax = position.x + size.x;
const float yMax = position.y + size.y;
//** TOP_LEFT **//
// top left
bufferMap[0].position = { xMin, yMin, position.z };
bufferMap[0].tint = tint;
//** TOP_RIGHT **//
// top right
bufferMap[1].position = { xMax, yMin, position.z };
bufferMap[1].tint = tint;
//** BOTTOM_RIGHT **//
// bottom right
bufferMap[2].position = { xMax, yMax, position.z };
bufferMap[2].tint = tint;
//** BOTTOM_LEFT **//
// bottom left
bufferMap[3].position = { xMin, yMax, position.z };
bufferMap[3].tint = tint;
@ -77,7 +81,9 @@ namespace Light {
FlushScene();
}
}
//======================================== DRAW_QUAD_TINT ========================================//
//============================== DRAW_QUAD_TEXTURE ==============================//
void Renderer::DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, Ref<Texture> texture)
{
// #todo: implement a proper binding
@ -91,19 +97,19 @@ namespace Light {
const float xMax = position.x + size.x;
const float yMax = position.y + size.y;
//** TOP_LEFT **//
// top left
bufferMap[0].position = { xMin, yMin, position.z };
bufferMap[0].texcoord = { 0.0f, 0.0f };
//** TOP_RIGHT **//
// top right
bufferMap[1].position = { xMax, yMin, position.z };
bufferMap[1].texcoord = { 1.0f, 0.0f };
//** BOTTOM_RIGHT **//
// bottom right
bufferMap[2].position = { xMax, yMax, position.z };
bufferMap[2].texcoord = { 1.0f, 1.0f };
//** BOTTOM_LEFT **//
// bottom left
bufferMap[3].position = { xMin, yMax, position.z };
bufferMap[3].texcoord = { 0.0f, 1.0f };
@ -114,6 +120,7 @@ namespace Light {
FlushScene();
}
}
//============================== DRAW_QUAD_TEXTURE ==============================//
void Renderer::BeginFrame()
{
@ -127,6 +134,7 @@ namespace Light {
void Renderer::BeginSceneImpl(const Ref<Camera>& camera, const Ref<Framebuffer>& targetFrameBuffer /* = nullptr */)
{
// determine the target frame buffer
m_TargetFramebuffer = targetFrameBuffer;
if (targetFrameBuffer)
@ -134,12 +142,13 @@ namespace Light {
else
m_RenderCommand->DefaultTargetFramebuffer();
// update view projection buffer
m_Camera = camera;
glm::mat4* map = (glm::mat4*)m_ViewProjectionBuffer->Map();
map[0] = m_Camera->GetProjection() * m_Camera->GetView();
m_ViewProjectionBuffer->UnMap();
// map renderers
m_QuadRenderer.Map();
m_TextureRenderer.Map();
}
@ -154,25 +163,26 @@ namespace Light {
void Renderer::EndSceneImpl()
{
// m_Blender->Disable();
// enable blending
m_Blender->Enable(BlendFactor::SRC_ALPHA, BlendFactor::INVERSE_SRC_ALPHA);
m_QuadRenderer.UnMap();
m_TextureRenderer.UnMap();
//** QUAD_RENDERER **//
/* quad renderer */
m_QuadRenderer.UnMap();
if (m_QuadRenderer.GetQuadCount())
{
m_QuadRenderer.Bind();
m_RenderCommand->DrawIndexed(m_QuadRenderer.GetQuadCount() * 6u);
}
//** TEXT_RENDERER **//
/* text renderer */
m_TextureRenderer.UnMap();
if (m_TextureRenderer.GetQuadCount())
{
m_TextureRenderer.Bind();
m_RenderCommand->DrawIndexed(m_TextureRenderer.GetQuadCount() * 6u);
}
// reset frame buffer
if(m_TargetFramebuffer)
{
m_TargetFramebuffer = nullptr;

View file

@ -1,10 +1,6 @@
#pragma once
#include "Base.h"
#include "Buffers.h"
#include "Blender.h"
#include "Framebuffer.h"
#include "Base/Base.h"
#include "RendererPrograms/QuadRendererProgram.h"
#include "RendererPrograms/TextureRendererProgram.h"
@ -16,19 +12,18 @@ struct GLFWwindow;
namespace Light {
class RenderCommand;
class Blender;
class ConstantBuffer;
class Framebuffer;
class RenderCommand;
class Texture;
class SharedContext;
class Camera;
class Texture;
class WindowResizedEvent;
class SharedContext;
class Renderer
{
private:
@ -44,15 +39,12 @@ namespace Light {
Scope<RenderCommand> m_RenderCommand;
Scope<Blender> m_Blender;
Ref<Framebuffer> m_TargetFramebuffer;
Ref<Camera> m_Camera;
Ref<Framebuffer> m_TargetFramebuffer;
public:
static Scope<Renderer> Create(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext);
static inline void SetTargetFramebuffer(Ref<Framebuffer> framebuffer) { s_Context->SetTargetFramebufferImpl(framebuffer); }
static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint) { s_Context->DrawQuadImpl(position, size, tint); }
static inline void DrawQuad(const glm::vec3& position, const glm::vec2& size, Ref<Texture> texture) { s_Context->DrawQuadImpl(position, size, texture); }
@ -67,8 +59,6 @@ namespace Light {
private:
Renderer(GLFWwindow* windowHandle, Ref<SharedContext> sharedContext);
void SetTargetFramebufferImpl(Ref<Framebuffer> framebuffer);
void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, const glm::vec4& tint);
void DrawQuadImpl(const glm::vec3& position, const glm::vec2& size, Ref<Texture> texture);

View file

@ -12,8 +12,15 @@
namespace Light {
QuadRendererProgram::QuadRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext)
: m_MaxVertices(maxVertices)
: m_Shader(nullptr),
m_IndexBuffer(nullptr),
m_VertexLayout(nullptr),
m_MapCurrent(nullptr),
m_MapEnd(nullptr),
m_QuadCount(0u),
m_MaxVertices(maxVertices)
{
// #todo: don't use relative path
ResourceManager::LoadShader("LT_ENGINE_RESOURCES_QUAD_SHADER", "../Engine/res/Shaders/Quad/Quad_VS", "../Engine//res/Shaders/Quad/Quad_PS");
m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_QUAD_SHADER");
@ -36,12 +43,6 @@ namespace Light {
return true;
}
void QuadRendererProgram::SetCamera(const Camera& camera)
{
m_Shader->Bind();
m_Shader->SetUniformMat4("u_ViewProjection", camera.GetProjection() * camera.GetView());
}
void QuadRendererProgram::Map()
{
m_QuadCount = 0u;

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "RendererProgram.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
namespace Light {
@ -41,8 +42,6 @@ namespace Light {
QuadRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext);
bool Advance();
void SetCamera(const Camera& camera) override;
void Map() override;
void UnMap() override;

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {
@ -8,9 +8,6 @@ namespace Light {
class RendererProgram
{
virtual void SetCamera(const Camera& camera) = 0;
virtual void Map() = 0;
virtual void UnMap() = 0;

View file

@ -12,8 +12,15 @@
namespace Light {
TextureRendererProgram::TextureRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext)
: m_MaxVertices(maxVertices)
: m_Shader(nullptr),
m_IndexBuffer(nullptr),
m_VertexLayout(nullptr),
m_MapCurrent(nullptr),
m_MapEnd(nullptr),
m_QuadCount(0u),
m_MaxVertices(maxVertices)
{
// #todo: don't use relative path
ResourceManager::LoadShader("LT_ENGINE_RESOURCES_TEXTURE_SHADER", "../Engine/res/Shaders/Texture/Texture_VS", "../Engine/res/Shaders/Texture/Texture_PS");
m_Shader = ResourceManager::GetShader("LT_ENGINE_RESOURCES_TEXTURE_SHADER");
@ -36,12 +43,6 @@ namespace Light {
return true;
}
void TextureRendererProgram::SetCamera(const Camera& camera)
{
m_Shader->Bind();
m_Shader->SetUniformMat4("u_ViewProjection", camera.GetProjection() * camera.GetView());
}
void TextureRendererProgram::Map()
{
m_QuadCount = 0u;
@ -62,4 +63,5 @@ namespace Light {
m_VertexBuffer->Bind();
m_IndexBuffer->Bind();
}
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "RendererProgram.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
namespace Light {
@ -34,23 +35,23 @@ namespace Light {
TextureVertexData* m_MapCurrent = nullptr;
TextureVertexData* m_MapEnd = nullptr;
unsigned int m_QuadCount = 0u;
unsigned int m_MaxVertices = 0u;
unsigned int m_QuadCount;
unsigned int m_MaxVertices;
public:
TextureRendererProgram(unsigned int maxVertices, Ref<SharedContext> sharedContext);
bool Advance();
void SetCamera(const Camera& camera) override;
void Map() override;
void UnMap() override;
void Bind() override;
inline TextureVertexData* GetMapCurrent() { return m_MapCurrent; }
inline unsigned int GetQuadCount() const { return m_QuadCount; }
inline constexpr unsigned int GetVertexSize() const { return sizeof(TextureVertexData); }
};

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
@ -18,14 +18,8 @@ namespace Light {
virtual void Bind() = 0;
virtual void UnBind() = 0;
//** #TEMP_SHADER_UNIFORMS_TEMP# **//
virtual void SetUniformMat4(const std::string& name, const glm::mat4& value) = 0;
protected:
Shader() = default;
private:
static void ExtractShaderSource(std::string& src, const std::string& delim);
};
}

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {

View file

@ -17,6 +17,13 @@ namespace Light {
}
Input::Input()
: m_KeyboadKeys{},
m_MouseButtons{},
m_MousePosition{},
m_MouseDelta{},
m_MouseWheelDelta{},
m_UserInterfaceEvents(true),
m_GameEvents(true)
{
LT_ENGINE_ASSERT(!s_Context, "Input::Input: an instance of 'Input' already exists, do not construct this class!");
s_Context = this;

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <glm/glm.hpp>
@ -20,8 +20,9 @@ namespace Light {
glm::vec2 m_MouseDelta;
float m_MouseWheelDelta;
bool m_UserInterfaceEvents = true;
bool m_GameEvents = true;
bool m_UserInterfaceEvents;
bool m_GameEvents;
public:
static Scope<Input> Create();

View file

@ -10,7 +10,7 @@ namespace Light {
{
enum : uint16_t
{
/* DIGITS */
/* digits */
D0 = 48,
D1 = 49,
D2 = 50,
@ -24,7 +24,7 @@ namespace Light {
Semicolon = 59, // ;
Equal = 61, // =
/* LETTERS */
/* letters */
A = 65,
B = 66,
C = 67,
@ -52,13 +52,13 @@ namespace Light {
Y = 89,
Z = 90,
/* BRACKETS */
/* brackets */
LeftBracket = 91, // [
LBracket = LeftBracket, // [
RightBracket = 93, // ]
RBracket = RightBracket, // ]
/* ARROW */
/* arrow */
Right = 262,
RightArrow = Right,
RArrow = Right,
@ -72,25 +72,21 @@ namespace Light {
UpArrow = Up,
UArrow = Up,
/* PAGE */
/* page */
PageUp = 266,
PageDown = 267,
/* HOME/END */
/* home/end */
Home = 268,
End = 269,
/* LOCKS */
/* toggles */
CapsLock = 280,
ScrollLock = 281,
NumLock = 282,
NumberLock = NumLock,
PrintScreen = 283,
Pause = 284,
/* FUNCTION */
/* function */
F1 = 290,
F2 = 291,
F3 = 292,
@ -117,7 +113,7 @@ namespace Light {
F24 = 313,
F25 = 314,
/* KEYPAD */
/* keypad */
Kp0 = 320,
Kp1 = 321,
Kp2 = 322,
@ -136,7 +132,7 @@ namespace Light {
KpEnter = 335,
KpEqual = 336,
/* Modifiers */
/* modifiers */
LeftShift = 340,
LShift = LeftShift,
LeftControl = 341,
@ -154,10 +150,17 @@ namespace Light {
RightSuper = 347,
RSuper = 347,
/* MISC */
/* misc */
Space = 32,
Apostrophe = 39, // '
Quote = Apostrophe,
Comma = 44, // ,
Minus = 45, // -
Period = 46, // .
Slash = 47, // /
ForwardSlash = Slash, // /
BackSlash = 92, // \
GraveAccent = 96, // `
Console = GraveAccent,
@ -171,14 +174,11 @@ namespace Light {
Insert = 260,
Delete = 261,
Comma = 44, // ,
Minus = 45, // -
Period = 46, // .
Slash = 47, // /
ForwardSlash = Slash, // /
BackSlash = 92, // \
PrintScreen = 283,
Pause = 284,
Menu = 348,
};
}

View file

@ -10,18 +10,18 @@ namespace Light {
{
enum : uint8_t
{
Button1 = 0,
Button2 = 1,
Button3 = 2,
Button4 = 3,
Button5 = 4,
Button6 = 5,
Button7 = 6,
Button8 = 7,
LButton = Button1,
RButton = Button2,
MButton = Button3,
Button1 = 0,
Button2 = 1,
Button3 = 2,
Button4 = 3,
Button5 = 4,
Button6 = 5,
Button7 = 6,
Button8 = 7,
LButton = Button1,
RButton = Button2,
MButton = Button3,
};
}

View file

@ -2,17 +2,22 @@
#include "Layer.h"
#include "Events/Event.h"
#include "Events/MouseEvents.h"
#include "Events/KeyboardEvents.h"
#include "Events/MouseEvents.h"
#include "Events/WindowEvents.h"
namespace Light {
Layer::Layer(const std::string& name)
: m_LayerName(name)
{
}
bool Layer::OnEvent(const Event& event)
{
switch (event.GetEventType())
{
//** MOUSE_EVENTS **//
/* mouse */
case EventType::MouseMoved:
return OnMouseMoved((MouseMovedEvent&)event);
case EventType::ButtonPressed:
@ -22,13 +27,13 @@ namespace Light {
case EventType::WheelScrolled:
return OnWheelScrolled((WheelScrolledEvent&)event);
//** KEYBOARD_EVENTS **//
/* keyboard */
case EventType::KeyPressed:
return OnKeyPressed((KeyPressedEvent&)event);
case EventType::KeyReleased:
return OnKeyReleased((KeyReleasedEvent&)event);
//** WINDOW_EVENTS **//
/* window */
case EventType::WindowClosed:
return OnWindowClosed((WindowClosedEvent&)event);
case EventType::WindowResized:

View file

@ -1,19 +1,22 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {
class Event;
// mouse
class MouseMovedEvent;
class ButtonPressedEvent;
class ButtonReleasedEvent;
class WheelScrolledEvent;
// keyboard
class KeyPressedEvent;
class KeyReleasedEvent;
// window
class WindowClosedEvent;
class WindowResizedEvent;
class WindowMovedEvent;
@ -26,12 +29,12 @@ namespace Light {
std::string m_LayerName;
public:
Layer(const std::string& name): m_LayerName(name) {}
Layer(const std::string& name);
virtual ~Layer() = default;
inline const std::string& GetName() const { return m_LayerName; }
//** UPDATES //
/* update */
virtual void OnUpdate(float deltaTime) {}
virtual void OnUserInterfaceUpdate() {}
@ -40,17 +43,17 @@ namespace Light {
bool OnEvent(const Event& event);
protected:
//** MOUSE_EVENTS //
/* mouse */
virtual bool OnMouseMoved(const MouseMovedEvent& event) { return false; }
virtual bool OnButtonPressed(const ButtonPressedEvent& event) { return false; }
virtual bool OnButtonReleased(const ButtonReleasedEvent& event) { return false; }
virtual bool OnWheelScrolled(const WheelScrolledEvent& event) { return false; }
//** KEYBOARD_EVENTS **//
/* keyboard */
virtual bool OnKeyPressed(const KeyPressedEvent& event) { return false; }
virtual bool OnKeyReleased(const KeyReleasedEvent& event) { return false; }
//** WINDOW_EVENTS **/
/* window */
virtual bool OnWindowClosed(const WindowClosedEvent& event) { return false; }
virtual bool OnWindowResized(const WindowResizedEvent& event) { return false; }
virtual bool OnWindowMoved(const WindowMovedEvent& event) { return false; }

View file

@ -18,6 +18,9 @@ namespace Light {
}
LayerStack::LayerStack()
: m_Layers{},
m_Begin(),
m_End()
{
LT_ENGINE_ASSERT(!s_Context, "LayerStack::LayerStack: an instance of 'LayerStack' already exists, do not construct this class!")
s_Context = this;

View file

@ -1,10 +1,11 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {
class Layer;
class Event;
class LayerStack
@ -22,7 +23,7 @@ namespace Light {
~LayerStack();
// #todo: should we keep this?
// #todo: is this needed?
template<typename T, typename... Args>
static inline void EmplaceLayer(Args&&... args) { s_Context->AttachLayerImpl(new T((args)...)); }

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <glm/glm.hpp>

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include "Scene.h"
@ -15,8 +15,7 @@ namespace Light {
Scene* m_Scene;
public:
Entity(){}
Entity(entt::entity handle, Scene* registry);
Entity(entt::entity handle = entt::entity(), Scene* registry = nullptr);
~Entity();
template<typename T, typename... Args>
@ -24,7 +23,6 @@ namespace Light {
{
return m_Scene->m_Registry.emplace<T>(m_Handle, std::forward<Args>(args)...);
}
};
}

View file

@ -1,8 +1,8 @@
#include "ltpch.h"
#include "Scene.h"
#include "Entity.h"
#include "Components.h"
#include "Entity.h"
#include "Graphics/Renderer.h"
@ -11,6 +11,7 @@
namespace Light {
Scene::Scene()
: m_Registry()
{
}
@ -22,10 +23,9 @@ namespace Light {
{
auto group = m_Registry.group(entt::get<TransformComponent, SpriteRendererComponent>);
group.each([](TransformComponent& transform, SpriteRendererComponent& sprite) {
group.each([](auto& transform, auto& sprite) {
Renderer::DrawQuad(glm::vec3(transform.position, 0.0f), transform.size, sprite.texture);
});
}
Entity Scene::CreateEntity(const std::string& name, const glm::vec2& position, const glm::vec2& size)
@ -34,7 +34,6 @@ namespace Light {
entity.AddComponent<TransformComponent>(position, size);
return entity;
}
}

View file

@ -1,11 +1,11 @@
#pragma once
#include "Base.h"
#include <glm/glm.hpp>
#include "Base/Base.h"
#include <entt.hpp>
#include <glm/glm.hpp>
namespace Light {
class Entity;

View file

@ -3,6 +3,17 @@
namespace Light {
Timer::Timer()
: m_Start(std::chrono::steady_clock::now())
{
}
DeltaTimer::DeltaTimer()
: m_PreviousFrame(NULL),
m_DeltaTime(60.0f / 1000.0f)
{
}
void DeltaTimer::Update()
{
float currentFrame = timer.GetElapsedTime();

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include <chrono>
@ -12,7 +12,7 @@ namespace Light {
std::chrono::time_point<std::chrono::steady_clock> m_Start;
public:
Timer() : m_Start(std::chrono::steady_clock::now()) { }
Timer();
inline float GetElapsedTime() const { return (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - m_Start).count()) / 1000.; }
@ -24,10 +24,12 @@ namespace Light {
private:
Timer timer;
float m_PreviousFrame = 0.0f;
float m_DeltaTime = 60.0f / 1000.0f;
float m_PreviousFrame;
float m_DeltaTime;
public:
DeltaTimer();
void Update();
inline float GetDeltaTime() const { return m_DeltaTime; }

View file

@ -7,12 +7,12 @@
#include "DirectX/dxSharedContext.h"
#endif
#include "Graphics/GraphicsContext.h"
#include "Events/Event.h"
#include "Events/MouseEvents.h"
#include "Events/KeyboardEvents.h"
#include "Graphics/GraphicsContext.h"
#include <imgui.h>
namespace Light {
@ -38,7 +38,7 @@ namespace Light {
ImGuiIO& io = ImGui::GetIO();
switch (inputEvent.GetEventType())
{
//** MOUSE_EVENTS **//
/* mouse events */
case EventType::MouseMoved:
{
const MouseMovedEvent& event = (const MouseMovedEvent&)inputEvent;
@ -63,7 +63,7 @@ namespace Light {
ImGui::GetIO().MouseWheel = event.GetOffset();
return;
}
//** MOUSE_EVENTS **//
/* keyboard events */
case EventType::KeyPressed:
{
const KeyPressedEvent& event = (const KeyPressedEvent&)inputEvent;

View file

@ -1,12 +1,13 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
struct GLFWwindow;
namespace Light {
class Event;
class SharedContext;
class UserInterface

View file

@ -17,7 +17,9 @@ namespace Light {
}
ResourceManager::ResourceManager(Ref<SharedContext> sharedContext)
: m_SharedContext(sharedContext)
: m_SharedGraphicsContext(sharedContext),
m_Shaders{},
m_Textures{}
{
LT_ENGINE_ASSERT(!s_Context, "ResourceManager::ResourceManager: an instance of 'ResourceManager' already exists, do not construct this class!");
s_Context = this;
@ -45,7 +47,7 @@ namespace Light {
ResourceManager::ExtractShaderSource(psSource, delim);
// create shader
m_Shaders[name] = Ref<Shader>(Shader::Create(vsSource, psSource, m_SharedContext));
m_Shaders[name] = Ref<Shader>(Shader::Create(vsSource, psSource, m_SharedGraphicsContext));
}
void ResourceManager::LoadShaderImpl(const std::string& name, const std::string& vertexPath, const std::string& pixelPath)
@ -70,7 +72,7 @@ namespace Light {
psSS << line << '\n';
// create shader
m_Shaders[name] = Ref<Shader>(Shader::Create(vsSS.str(), psSS.str(), m_SharedContext));
m_Shaders[name] = Ref<Shader>(Shader::Create(vsSS.str(), psSS.str(), m_SharedGraphicsContext));
}
void ResourceManager::LoadTextureImpl(const std::string& name, const std::string& path, unsigned int desiredComponents /* = 4u */)
@ -88,7 +90,7 @@ namespace Light {
}
// create texture
m_Textures[name] = Ref<Texture>(Texture::Create(width, height, components, pixels, m_SharedContext));
m_Textures[name] = Ref<Texture>(Texture::Create(width, height, components, pixels, m_SharedGraphicsContext));
}
void ResourceManager::ExtractShaderSource(std::string& src, const std::string& delim)

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {
@ -15,11 +15,11 @@ namespace Light {
private:
static ResourceManager* s_Context;
Ref<SharedContext> m_SharedGraphicsContext;
std::unordered_map<std::string, Ref<Shader>> m_Shaders;
std::unordered_map<std::string, Ref<Texture>> m_Textures;
Ref<SharedContext> m_SharedContext;
public:
static Scope<ResourceManager> Create(Ref<SharedContext> sharedContext);
@ -39,6 +39,7 @@ namespace Light {
void LoadShaderImpl(const std::string& name, const std::string& vertexPath, const std::string& pixelPath);
void LoadTextureImpl(const std::string& name, const std::string& path, unsigned int desiredComponents = 4u);
private:
void ExtractShaderSource(std::string& src, const std::string& delim);
};

View file

@ -9,6 +9,7 @@
namespace Light {
//============================== OPENGL ==============================//
std::string Stringifier::glDebugMsgSeverity(unsigned int severity)
{
switch (severity)
@ -51,7 +52,9 @@ namespace Light {
default: return "UNKNOWN";
}
}
//============================== OPENGL ==============================//
//==================== SPDLOG ====================//
std::string Stringifier::spdlogLevel(unsigned int level)
{
switch (level)
@ -66,7 +69,9 @@ namespace Light {
default: return "UNKNOWN";
}
}
//==================== SPDLOG ====================//
//==================== GRAPHICS_API ====================//
std::string Stringifier::GraphicsAPIToString(GraphicsAPI api)
{
switch (api)
@ -79,5 +84,6 @@ namespace Light {
default: return "UNKNOWN";
}
}
//==================== GRAPHICS_API ====================//
}

View file

@ -1,7 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
namespace Light {

View file

@ -1,17 +1,16 @@
#pragma once
//** ENGINE **//
#include "Base.h"
/* engine */
#include "Base/Base.h"
//** PLATFORM SPECIFIC **//
// windows
/* windows */
#ifdef _WIN32
#define NOMINMAX
#include <Windows.h>
#undef NOMINMAX
#endif
//** CONTAINERS **//
/* containers */
#include <array>
#include <vector>
#include <list>
@ -21,29 +20,29 @@
#include <unordered_map>
#include <unordered_set>
//** MISCELLANEOUS **//
/* misc */
#include <algorithm>
#include <functional>
#include <memory>
#include <tuple>
#include <utility>
//** INPUT_OUTPUT **//
/* input/output */
#include <iostream>
#include <fstream>
#include <sstream>
//** MULTI_THREADING **//
/* multi threading */
#include <thread>
#include <atomic>
//** STRING **//
/* string */
#include <string>
#include <string_view>
//** FILESYSTEM **//
/* filesystem */
#include <filesystem>
//** C_LIBRARIES **//
/* c libraries */
#include <time.h>
#include <math.h>

View file

@ -1,56 +1,56 @@
#pragma once
//** CORE **//
// core
#include "Core/Application.h"
#include "Core/Window.h"
//** CAMERA **//
// camera
#include "Camera/Camera.h"
//** DEBUG **//
// debug
#include "Debug/Logger.h"
//** EVENTS **//
// events
#include "Events/Event.h"
#include "Events/KeyboardEvents.h"
#include "Events/MouseEvents.h"
#include "Events/WindowEvents.h"
//** GRAPHICS **//
// graphics
#include "Graphics/GraphicsContext.h"
#include "Graphics/Renderer.h"
#include "Graphics/Framebuffer.h"
//** INPUT **//
// input
#include "Input/Input.h"
#include "Input/KeyCodes.h"
#include "Input/MouseCodes.h"
//** LAYER **//
// layer
#include "Layer/Layer.h"
#include "Layer/LayerStack.h"
//** USER_INTERFACE **//
// user interface
#include "UserInterface/UserInterface.h"
//** UTILITY **//
// utility
#include "Utility/ResourceManager.h"
//** TIME **//
// time
#include "Time/Timer.h"
//** BASE **//
#include "Base.h"
// base
#include "Base/Base.h"
//** THIRD_PARTY **//
// third party
#include <imgui.h>
//** SCENE **//
// scene
#include "Scene/Scene.h"
#include "Scene/Entity.h"
#include "Scene/Components.h"
// entry point
#ifdef LIGHT_ENTRY_POINT
#include "EntryPoint.h"
#include "Base/EntryPoint.h"
#endif

View file

@ -1,41 +1,39 @@
#include "ltpch.h"
#include "dxBlender.h"
#include "dxSharedContext.h"
namespace Light {
dxBlender::dxBlender(Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext)
: m_Context(sharedContext),
m_FactorMap{ // constants
{ BlendFactor::ZERO, D3D11_BLEND_ZERO },
{ BlendFactor::ONE, D3D11_BLEND_ONE },
// source
{ BlendFactor::SRC_COLOR, D3D11_BLEND_SRC_COLOR },
{ BlendFactor::INVERSE_SRC_COLOR, D3D11_BLEND_INV_SRC_COLOR },
{ BlendFactor::SRC_ALPHA, D3D11_BLEND_SRC_ALPHA },
{ BlendFactor::INVERSE_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA },
// destination
{ BlendFactor::DST_COLOR, D3D11_BLEND_DEST_COLOR },
{ BlendFactor::INVERSE_DST_COLOR, D3D11_BLEND_INV_DEST_COLOR },
{ BlendFactor::DST_ALPHA, D3D11_BLEND_DEST_ALPHA },
{ BlendFactor::INVERSE_DST_ALPHA, D3D11_BLEND_INV_DEST_ALPHA },
// source1
{ BlendFactor::SRC1_COLOR, D3D11_BLEND_SRC1_COLOR },
{ BlendFactor::INVERSE_SRC1_COLOR, D3D11_BLEND_INV_SRC1_COLOR },
{ BlendFactor::SRC1_ALPHA, D3D11_BLEND_SRC1_ALPHA },
{ BlendFactor::INVERSE_SRC1_ALPHA, D3D11_BLEND_INV_SRC1_ALPHA } },
m_BlendState(nullptr),
m_Desc{}
{
// factor map
m_FactorMap = {
// constants
{ BlendFactor::ZERO, D3D11_BLEND_ZERO },
{ BlendFactor::ONE, D3D11_BLEND_ONE },
// source
{ BlendFactor::SRC_COLOR, D3D11_BLEND_SRC_COLOR },
{ BlendFactor::INVERSE_SRC_COLOR, D3D11_BLEND_INV_SRC_COLOR },
{ BlendFactor::SRC_ALPHA, D3D11_BLEND_SRC_ALPHA },
{ BlendFactor::INVERSE_SRC_ALPHA, D3D11_BLEND_INV_SRC_ALPHA },
// destination
{ BlendFactor::DST_COLOR, D3D11_BLEND_DEST_COLOR },
{ BlendFactor::INVERSE_DST_COLOR, D3D11_BLEND_INV_DEST_COLOR },
{ BlendFactor::DST_ALPHA, D3D11_BLEND_DEST_ALPHA },
{ BlendFactor::INVERSE_DST_ALPHA, D3D11_BLEND_INV_DEST_ALPHA },
// source1
{ BlendFactor::SRC1_COLOR, D3D11_BLEND_SRC1_COLOR },
{ BlendFactor::INVERSE_SRC1_COLOR, D3D11_BLEND_INV_SRC1_COLOR },
{ BlendFactor::SRC1_ALPHA, D3D11_BLEND_SRC1_ALPHA },
{ BlendFactor::INVERSE_SRC1_ALPHA, D3D11_BLEND_INV_SRC1_ALPHA }
};
// blender desc
m_Desc = { };
@ -57,8 +55,8 @@ namespace Light {
{
// update desc
m_Desc.RenderTarget[0].BlendEnable = true;
m_Desc.RenderTarget[0].SrcBlend = m_FactorMap[srcFactor];
m_Desc.RenderTarget[0].DestBlend = m_FactorMap[dstFactor];
m_Desc.RenderTarget[0].SrcBlend = m_FactorMap.at(srcFactor);
m_Desc.RenderTarget[0].DestBlend = m_FactorMap.at(dstFactor);
// re-create blind state
HRESULT hr;

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/Blender.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>
@ -14,7 +15,8 @@ namespace Light {
{
private:
Ref<dxSharedContext> m_Context;
std::unordered_map<BlendFactor, D3D11_BLEND> m_FactorMap;
const std::unordered_map<BlendFactor, D3D11_BLEND> m_FactorMap;
Microsoft::WRL::ComPtr<ID3D11BlendState> m_BlendState;

View file

@ -1,22 +1,25 @@
#include "ltpch.h"
#include "dxBuffers.h"
#include "dxSharedContext.h"
namespace Light {
//======================================== CONSTANT_BUFFER ========================================//
dxConstantBuffer::dxConstantBuffer(ConstantBufferIndex index, unsigned int size, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext), m_Index((int)index)
: m_Context(sharedContext),
m_Buffer(nullptr),
m_Map{},
m_Index(static_cast<int>(index))
{
D3D11_BUFFER_DESC bufferDesc = { };
D3D11_BUFFER_DESC bDesc = {};
bufferDesc.ByteWidth = size;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bDesc.ByteWidth = size;
bDesc.Usage = D3D11_USAGE_DYNAMIC;
bDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
HRESULT hr;
DXC(m_Context->GetDevice()->CreateBuffer(&bufferDesc, nullptr, &m_Buffer));
DXC(m_Context->GetDevice()->CreateBuffer(&bDesc, nullptr, &m_Buffer));
m_Context->GetDeviceContext()->VSSetConstantBuffers(m_Index, 1u, m_Buffer.GetAddressOf());
}
@ -36,24 +39,28 @@ namespace Light {
{
m_Context->GetDeviceContext()->Unmap(m_Buffer.Get(), NULL);
}
//======================================== CONSTANT_BUFFER ========================================//
//* VERTEX_BUFFER *//
//================================================== VERTEX_BUFFER ==================================================//
dxVertexBuffer::dxVertexBuffer(float* vertices, unsigned int stride, unsigned int count, Ref<dxSharedContext> sharedContext)
: m_Stride(stride), m_Context(sharedContext)
: m_Context(sharedContext),
m_Buffer(nullptr),
m_Map{},
m_Stride(stride)
{
// buffer desc
D3D11_BUFFER_DESC bd = { 0 };
D3D11_BUFFER_DESC bDesc = {};
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bDesc.Usage = D3D11_USAGE_DYNAMIC;
bDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.ByteWidth = count * stride;
bd.StructureByteStride = stride;
bDesc.ByteWidth = count * stride;
bDesc.StructureByteStride = stride;
// create buffer
HRESULT hr;
DXC(m_Context->GetDevice()->CreateBuffer(&bd, nullptr, &m_Buffer));
DXC(m_Context->GetDevice()->CreateBuffer(&bDesc, nullptr, &m_Buffer));
}
dxVertexBuffer::~dxVertexBuffer()
@ -85,10 +92,12 @@ namespace Light {
m_Context->GetDeviceContext()->IASetVertexBuffers(0u, 1u, &buffer, &m_Stride, &offset);
}
//================================================== VERTEX_BUFFER ==================================================//
//* INDEX_BUFFER *//
//======================================== INDEX_BUFFER ========================================//
dxIndexBuffer::dxIndexBuffer(unsigned int* indices, unsigned int count, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext)
: m_Context(sharedContext),
m_Buffer(nullptr)
{
// generate indices if not provided
bool hasIndices = !!indices;
@ -107,33 +116,33 @@ namespace Light {
unsigned int offset = 0;
for (unsigned int i = 0; i < count; i += 6)
{
indices[i + 0] = offset + 0;
indices[i + 1] = offset + 3;
indices[i + 2] = offset + 2;
indices[i + 0] = offset + 0u;
indices[i + 1] = offset + 3u;
indices[i + 2] = offset + 2u;
indices[i + 3] = offset + 2;
indices[i + 4] = offset + 1;
indices[i + 5] = offset + 0;
indices[i + 3] = offset + 2u;
indices[i + 4] = offset + 1u;
indices[i + 5] = offset + 0u;
offset += 4;
offset += 4u;
}
}
// buffer desc
D3D11_BUFFER_DESC bd = { 0 };
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.Usage = D3D11_USAGE_DEFAULT;
D3D11_BUFFER_DESC bDesc = {};
bDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
bDesc.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = count * sizeof(unsigned int);
bd.StructureByteStride = sizeof(unsigned int);
bDesc.ByteWidth = count * sizeof(unsigned int);
bDesc.StructureByteStride = sizeof(unsigned int);
// subresource data
D3D11_SUBRESOURCE_DATA sd = { 0 };
sd.pSysMem = indices;
D3D11_SUBRESOURCE_DATA sDesc = {};
sDesc.pSysMem = indices;
// create buffer
HRESULT hr;
DXC(m_Context->GetDevice()->CreateBuffer(&bd, &sd, &m_Buffer));
DXC(m_Context->GetDevice()->CreateBuffer(&bDesc, &sDesc, &m_Buffer));
// delete indices
if (!hasIndices)
@ -157,5 +166,6 @@ namespace Light {
m_Context->GetDeviceContext()->IASetIndexBuffer(buffer, DXGI_FORMAT_R32_UINT, offset);
}
//======================================== INDEX_BUFFER ========================================//
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/Buffers.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>
@ -10,7 +11,7 @@ namespace Light {
class dxSharedContext;
//* INDEX_BUFFER *//
//========== CONSTANT_BUFFER ==========//
class dxConstantBuffer : public ConstantBuffer
{
private:
@ -30,7 +31,7 @@ namespace Light {
void UnMap() override;
};
//* VERTEX_BUFFER *//
//========== VERTEX_BUFFER ==========//
class dxVertexBuffer : public VertexBuffer
{
private:
@ -45,14 +46,14 @@ namespace Light {
dxVertexBuffer(float* vertices, unsigned int stride, unsigned int count, Ref<dxSharedContext> sharedContext);
~dxVertexBuffer();
void* Map() override;
void UnMap() override;
void Bind() override;
void UnBind() override;
void* Map() override;
void UnMap() override;
};
//* INDEX_BUFFER *//
//========== INDEX_BUFFER ==========//
class dxIndexBuffer : public IndexBuffer
{
private:

View file

@ -5,32 +5,39 @@
namespace Light {
dxFramebuffer::dxFramebuffer(const FramebufferSpecification& specification, Ref<dxSharedContext> sharedContext)
: m_Specification(specification), m_Context(sharedContext)
: m_Context(sharedContext),
m_Specification(specification),
m_RenderTargetView(nullptr),
m_ColorAttachment(nullptr),
m_DepthStencilAttachment(nullptr),
m_ShaderResourceView(nullptr),
m_DepthStencilView(nullptr)
{
HRESULT hr;
D3D11_TEXTURE2D_DESC textureDesc = { };
textureDesc.Width = specification.width;
textureDesc.Height = specification.height;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.SampleDesc.Count = 1u;
textureDesc.SampleDesc.Quality = 0u;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = NULL;
textureDesc.MiscFlags = NULL;
DXC(m_Context->GetDevice()->CreateTexture2D(&textureDesc, nullptr, &m_ColorAttachment));
D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc = { };
shaderResourceViewDesc.Format = textureDesc.Format;
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MipLevels = 1;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
DXC(m_Context->GetDevice()->CreateShaderResourceView(m_ColorAttachment.Get(), &shaderResourceViewDesc, &m_ResourceView));
D3D11_TEXTURE2D_DESC t2dDesc = {};
t2dDesc.Width = specification.width;
t2dDesc.Height = specification.height;
t2dDesc.MipLevels = 1;
t2dDesc.ArraySize = 1;
t2dDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
t2dDesc.SampleDesc.Count = 1u;
t2dDesc.SampleDesc.Quality = 0u;
t2dDesc.Usage = D3D11_USAGE_DEFAULT;
t2dDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
t2dDesc.CPUAccessFlags = NULL;
t2dDesc.MiscFlags = NULL;
DXC(m_Context->GetDevice()->CreateTexture2D(&t2dDesc, nullptr, &m_ColorAttachment));
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = t2dDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
srvDesc.Texture2D.MostDetailedMip = 0;
DXC(m_Context->GetDevice()->CreateShaderResourceView(m_ColorAttachment.Get(), &srvDesc, &m_ShaderResourceView));
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc = {};
rtvDesc.Format = textureDesc.Format;
rtvDesc.Format = t2dDesc.Format;
rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
rtvDesc.Texture2D.MipSlice = 0u;
DXC(m_Context->GetDevice()->CreateRenderTargetView(m_ColorAttachment.Get(), &rtvDesc, &m_RenderTargetView));
@ -68,10 +75,10 @@ namespace Light {
LT_ENGINE_ERROR("dxFramebuffer::BindAsResource: NO_IMPLEMENT");
}
void dxFramebuffer::Resize(const glm::vec2& size)
void dxFramebuffer::Resize(const glm::uvec2& size)
{
m_Specification.width = std::clamp(size.x, 1.0f, 16384.0f);
m_Specification.height= std::clamp(size.y, 1.0f, 16384.0f);
m_Specification.width = std::clamp(size.x, 1u, 16384u);
m_Specification.height= std::clamp(size.y, 1u, 16384u);
D3D11_TEXTURE2D_DESC textureDesc;
D3D11_RENDER_TARGET_VIEW_DESC rtvDesc;
@ -79,7 +86,7 @@ namespace Light {
m_ColorAttachment->GetDesc(&textureDesc);
m_RenderTargetView->GetDesc(&rtvDesc);
m_ResourceView->GetDesc(&srvDesc);
m_ShaderResourceView->GetDesc(&srvDesc);
textureDesc.Width = m_Specification.width;
textureDesc.Height = m_Specification.height;
@ -87,7 +94,7 @@ namespace Light {
HRESULT hr;
DXC(m_Context->GetDevice()->CreateTexture2D(&textureDesc, nullptr, &m_ColorAttachment));
DXC(m_Context->GetDevice()->CreateRenderTargetView(m_ColorAttachment.Get(), &rtvDesc, &m_RenderTargetView));
DXC(m_Context->GetDevice()->CreateShaderResourceView(m_ColorAttachment.Get(), &srvDesc, &m_ResourceView));
DXC(m_Context->GetDevice()->CreateShaderResourceView(m_ColorAttachment.Get(), &srvDesc, &m_ShaderResourceView));
}
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/Framebuffer.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>
@ -20,18 +21,18 @@ namespace Light {
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_RenderTargetView;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_ColorAttachment;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_DepthStencilAttachment;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_ResourceView;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_ShaderResourceView;
Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_DepthStencilView;
public:
dxFramebuffer(const FramebufferSpecification& specification, Ref<dxSharedContext> sharedContext);
inline void* GetColorAttachment() override { return (void*)m_ResourceView.Get(); }
inline void* GetColorAttachment() override { return (void*)m_ShaderResourceView.Get(); }
void BindAsTarget() override;
void BindAsResource() override;
void Resize(const glm::vec2& size) override;
void Resize(const glm::uvec2& size) override;
};
}

View file

@ -4,11 +4,14 @@
#include "Events/WindowEvents.h"
// forward declaration
#include "Graphics/Renderer.h"
#include "Graphics/RenderCommand.h"
#include "UserInterface/UserInterface.h"
#include "Utility/ResourceManager.h"
#include "Graphics/Blender.h" // required for forward declaration
#include "Graphics/Buffers.h" // required for forward declaration
#include "Graphics/Renderer.h" // required for forward declaration
#include "Graphics/RenderCommand.h" // required for forward declaration
#include "UserInterface/UserInterface.h" // required for forward declaration
#include "Utility/ResourceManager.h" // required for forward declaration
#define GLFW_EXPOSE_NATIVE_WIN32
#include <glfw/glfw3.h>
@ -17,7 +20,8 @@
namespace Light {
dxGraphicsContext::dxGraphicsContext(GLFWwindow* windowHandle)
: m_WindowHandle(windowHandle)
: m_WindowHandle(windowHandle),
m_DebugInterface(nullptr)
{
// set 'GraphicsAPI';
m_GraphicsAPI = GraphicsAPI::DirectX;

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/GraphicsContext.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>
@ -14,6 +15,7 @@ namespace Light {
{
private:
GLFWwindow* m_WindowHandle;
Microsoft::WRL::ComPtr<ID3D11Debug> m_DebugInterface;
public:

View file

@ -6,13 +6,14 @@ namespace Light {
dxRenderCommand::dxRenderCommand(Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext)
{ }
{
}
void dxRenderCommand::SwapBuffers()
{
#ifdef LIGHT_DEBUG
HRESULT hr;
if (FAILED(hr = m_Context->GetSwapChain()->Present(0u, 0u)))
if (FAILED(hr = m_Context->GetSwapChain()->Present(1u, 0u)))
{
if (hr == DXGI_ERROR_DEVICE_REMOVED)
{
@ -83,8 +84,9 @@ namespace Light {
Microsoft::WRL::ComPtr<ID3D11Resource> backBuffer = nullptr;
DXC(m_Context->GetSwapChain()->GetBuffer(0u, __uuidof(ID3D11Resource), &backBuffer));
DXC(m_Context->GetDevice()->CreateRenderTargetView(backBuffer.Get(), nullptr, &m_Context->GetRenderTargetViewRef()));
// set render target
m_Context->GetDeviceContext()->OMSetRenderTargets(1, m_Context->GetRenderTargetView().GetAddressOf(), nullptr);
m_Context->GetDeviceContext()->OMSetRenderTargets(1u, m_Context->GetRenderTargetView().GetAddressOf(), nullptr);
}
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/RenderCommand.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>

View file

@ -7,12 +7,14 @@
namespace Light {
dxShader::dxShader(const std::string& vertexSource, const std::string& pixelSource, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext)
: m_Context(sharedContext),
m_VertexShader(nullptr),
m_PixelShader(nullptr),
m_VertexBlob(nullptr)
{
Microsoft::WRL::ComPtr<ID3DBlob> ps = nullptr, vsErr = nullptr, psErr = nullptr;
// compile shaders
HRESULT hr;
// compile shaders (we don't use DXC here because if D3DCompile fails it throws a dxException without logging the vsErr/psErr)
D3DCompile(vertexSource.c_str(), vertexSource.length(), NULL, nullptr, nullptr, "main", "vs_4_0", NULL, NULL, &m_VertexBlob, &vsErr);
D3DCompile(pixelSource.c_str(), pixelSource.length(), NULL, nullptr, nullptr, "main", "ps_4_0", NULL, NULL, &ps, &psErr);
@ -21,6 +23,7 @@ namespace Light {
LT_ENGINE_ASSERT(!psErr.Get(), "dxShader::dxShader: pixels shader compile error: {}", (char*)psErr->GetBufferPointer());
// create shaders
HRESULT hr;
DXC(m_Context->GetDevice()->CreateVertexShader(m_VertexBlob->GetBufferPointer(), m_VertexBlob->GetBufferSize(), NULL, &m_VertexShader));
DXC(m_Context->GetDevice()->CreatePixelShader(ps->GetBufferPointer(), ps->GetBufferSize(), NULL, &m_PixelShader));
}
@ -42,9 +45,4 @@ namespace Light {
m_Context->GetDeviceContext()->PSSetShader(nullptr, nullptr, 0u);
}
void dxShader::SetUniformMat4(const std::string& name, const glm::mat4& value)
{
LT_ENGINE_ERROR("dxShader::SetUniformMat4: NOT_IMPLEMENTED");
}
}

View file

@ -1,9 +1,8 @@
#pragma once
#include "Base.h"
#include "Graphics/Shader.h"
#include <glm/glm.hpp>
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>
@ -29,9 +28,7 @@ namespace Light {
void Bind() override;
void UnBind() override;
void SetUniformMat4(const std::string& name, const glm::mat4& value) override;
Microsoft::WRL::ComPtr<ID3DBlob> GetVertexBlob() { return m_VertexBlob; }
inline Microsoft::WRL::ComPtr<ID3DBlob> GetVertexBlob() { return m_VertexBlob; }
};
}

View file

@ -1,6 +1,6 @@
#pragma once
#include "Base.h"
#include "Base/Base.h"
#include "Graphics/SharedContext.h"
#include <d3d11.h>
@ -8,7 +8,6 @@
namespace Light {
// #todo:
class dxSharedContext : public SharedContext
{
private:

View file

@ -5,61 +5,64 @@
namespace Light {
dxTexture::dxTexture(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext)
: m_Context(sharedContext),
m_Texture2D(nullptr),
m_ShaderResourceView(nullptr),
m_SamplerState(nullptr)
{
// texture desc
D3D11_TEXTURE2D_DESC textureDesc = { };
textureDesc.Width = width;
textureDesc.Height = height;
textureDesc.MipLevels = 0u;
textureDesc.ArraySize = 1u;
textureDesc.Format = components == 4u ? DXGI_FORMAT_R8G8B8A8_UNORM :
components == 3u ? DXGI_FORMAT_R8G8B8A8_UNORM :
components == 2u ? DXGI_FORMAT_R8G8B8A8_UNORM :
components == 1u ? DXGI_FORMAT_R8G8B8A8_UNORM : DXGI_FORMAT_UNKNOWN;
textureDesc.SampleDesc.Count = 1u;
textureDesc.SampleDesc.Quality = 0u;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
textureDesc.CPUAccessFlags = NULL;
textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
// texture2d desc
D3D11_TEXTURE2D_DESC t2dDesc = {};
t2dDesc.Width = width;
t2dDesc.Height = height;
t2dDesc.MipLevels = 0u;
t2dDesc.ArraySize = 1u;
t2dDesc.Format = components == 4u ? DXGI_FORMAT_R8G8B8A8_UNORM :
components == 3u ? DXGI_FORMAT_R8G8B8A8_UNORM : // #todo: figure out what to do with this bitch ._.
components == 2u ? DXGI_FORMAT_R8G8_UNORM :
components == 1u ? DXGI_FORMAT_R8_UNORM : DXGI_FORMAT_UNKNOWN;
t2dDesc.SampleDesc.Count = 1u;
t2dDesc.SampleDesc.Quality = 0u;
t2dDesc.Usage = D3D11_USAGE_DEFAULT;
t2dDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
t2dDesc.CPUAccessFlags = NULL;
t2dDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
// create texture
HRESULT hr;
DXC(m_Context->GetDevice()->CreateTexture2D(&textureDesc, nullptr, &m_Texture));
m_Context->GetDeviceContext()->UpdateSubresource(m_Texture.Get(), 0u, nullptr, pixels, width * 4u, 0u);
m_Texture->GetDesc(&textureDesc);
DXC(m_Context->GetDevice()->CreateTexture2D(&t2dDesc, nullptr, &m_Texture2D));
m_Context->GetDeviceContext()->UpdateSubresource(m_Texture2D.Get(), 0u, nullptr, pixels, width * 4u, 0u);
m_Texture2D->GetDesc(&t2dDesc);
// shader resource view desc
D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc = { };
shaderResourceViewDesc.Format = textureDesc.Format;
shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shaderResourceViewDesc.Texture2D.MostDetailedMip = 0u;
shaderResourceViewDesc.Texture2D.MipLevels = -1;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = t2dDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0u;
srvDesc.Texture2D.MipLevels = -1;
// create shader resource view
m_Context->GetDevice()->CreateShaderResourceView(m_Texture.Get(), &shaderResourceViewDesc, &m_ResourceView);
m_Context->GetDeviceContext()->GenerateMips(m_ResourceView.Get());
m_Context->GetDevice()->CreateShaderResourceView(m_Texture2D.Get(), &srvDesc, &m_ShaderResourceView);
m_Context->GetDeviceContext()->GenerateMips(m_ShaderResourceView.Get());
// sampler desc
D3D11_SAMPLER_DESC samplerDesc = { };
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MinLOD = 0.0f;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
D3D11_SAMPLER_DESC sDesc = {};
sDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sDesc.MinLOD = 0.0f;
sDesc.MipLODBias = 0.0f;
sDesc.MaxLOD = D3D11_FLOAT32_MAX;
// create sampler
m_Context->GetDevice()->CreateSamplerState(&samplerDesc, &m_SamplerState);
m_Context->GetDevice()->CreateSamplerState(&sDesc, &m_SamplerState);
}
void dxTexture::Bind(unsigned int slot /* = 0u */)
{
m_Context->GetDeviceContext()->PSSetSamplers(slot, 1u, m_SamplerState.GetAddressOf());
m_Context->GetDeviceContext()->PSSetShaderResources(slot, 1u, m_ResourceView.GetAddressOf());
m_Context->GetDeviceContext()->PSSetShaderResources(slot, 1u, m_ShaderResourceView.GetAddressOf());
}
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/Texture.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>
@ -15,8 +16,8 @@ namespace Light {
private:
Ref<dxSharedContext> m_Context;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_Texture;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_ResourceView;
Microsoft::WRL::ComPtr<ID3D11Texture2D> m_Texture2D;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_ShaderResourceView;
Microsoft::WRL::ComPtr<ID3D11SamplerState> m_SamplerState;
public:

View file

@ -2,14 +2,14 @@
#include "dxUserInterface.h"
#include "dxSharedContext.h"
#include <imgui.h>
#include <imgui_impl_win32.h>
#include <imgui_impl_dx11.h>
#define GLFW_EXPOSE_NATIVE_WIN32
#include <glfw/glfw3.h>
#include <glfw/glfw3native.h>
#include <imgui.h>
#include <imgui_impl_win32.h>
#include <imgui_impl_dx11.h>
namespace Light {
dxUserInterface::dxUserInterface(GLFWwindow* windowHandle, Ref<dxSharedContext> sharedContext)
@ -61,7 +61,7 @@ namespace Light {
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
//** #TEMP_IMGUI_DEMO_TEMP# **//
/* #TEMP_IMGUI_DEMO_TEMP# */
ImGui::ShowDemoWindow();
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "UserInterface/UserInterface.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>

View file

@ -7,7 +7,8 @@
namespace Light {
dxVertexLayout::dxVertexLayout(Ref<Shader> shader, const std::vector<std::pair<std::string, VertexElementType>>& elements, Ref<dxSharedContext> sharedContext)
: m_Context(sharedContext)
: m_Context(sharedContext),
m_InputLayout(nullptr)
{
// occupy space for input elements
std::vector<D3D11_INPUT_ELEMENT_DESC> inputElementsDesc;
@ -16,14 +17,13 @@ namespace Light {
// extract elements desc
for (const auto& element : elements)
{
inputElementsDesc.emplace_back(D3D11_INPUT_ELEMENT_DESC{
element.first.c_str(),
0u,
GetDxgiFormat(element.second),
0u,
D3D11_APPEND_ALIGNED_ELEMENT,
D3D11_INPUT_PER_VERTEX_DATA,
0u });
inputElementsDesc.emplace_back(D3D11_INPUT_ELEMENT_DESC{ element.first.c_str(),
NULL,
GetDxgiFormat(element.second),
0u,
D3D11_APPEND_ALIGNED_ELEMENT,
D3D11_INPUT_PER_VERTEX_DATA,
0u });
}
Ref<dxShader> dxpShader = std::dynamic_pointer_cast<dxShader>(shader);

View file

@ -1,14 +1,16 @@
#pragma once
#include "Base.h"
#include "Graphics/VertexLayout.h"
#include "Base/Base.h"
#include <d3d11.h>
#include <wrl.h>
namespace Light {
class Shader;
class dxSharedContext;
class dxVertexLayout : public VertexLayout

View file

@ -6,39 +6,37 @@
namespace Light {
glBlender::glBlender()
: m_FactorMap{ // constants
{ BlendFactor::ZERO , GL_ZERO },
{ BlendFactor::ONE , GL_ONE },
// source ,
{ BlendFactor::SRC_COLOR , GL_SRC_COLOR },
{ BlendFactor::INVERSE_SRC_COLOR , GL_ONE_MINUS_SRC_COLOR },
{ BlendFactor::SRC_ALPHA , GL_SRC_ALPHA },
{ BlendFactor::INVERSE_SRC_ALPHA , GL_ONE_MINUS_SRC_ALPHA },
// destination ,
{ BlendFactor::DST_COLOR , GL_DST_COLOR },
{ BlendFactor::INVERSE_DST_COLOR , GL_ONE_MINUS_DST_COLOR },
{ BlendFactor::DST_ALPHA , GL_DST_ALPHA },
{ BlendFactor::INVERSE_DST_ALPHA , GL_ONE_MINUS_DST_ALPHA },
// source1 ,
{ BlendFactor::SRC1_COLOR , GL_SRC1_COLOR },
{ BlendFactor::INVERSE_SRC1_COLOR, GL_ONE_MINUS_SRC1_COLOR },
{ BlendFactor::SRC1_ALPHA , GL_SRC1_ALPHA },
{ BlendFactor::INVERSE_SRC1_ALPHA, GL_ONE_MINUS_SRC_ALPHA } }
{
m_FactorMap = {
// constants
{ BlendFactor::ZERO, GL_ZERO },
{ BlendFactor::ONE, GL_ZERO },
// source
{ BlendFactor::SRC_COLOR, GL_SRC_COLOR },
{ BlendFactor::INVERSE_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR },
{ BlendFactor::SRC_ALPHA, GL_SRC_ALPHA },
{ BlendFactor::INVERSE_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA },
// destination
{ BlendFactor::DST_COLOR, GL_DST_COLOR },
{ BlendFactor::INVERSE_DST_COLOR, GL_ONE_MINUS_DST_COLOR },
{ BlendFactor::DST_ALPHA, GL_DST_ALPHA },
{ BlendFactor::INVERSE_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA },
// source1
{ BlendFactor::SRC1_COLOR, GL_SRC1_COLOR },
{ BlendFactor::INVERSE_SRC1_COLOR, GL_ONE_MINUS_SRC1_COLOR },
{ BlendFactor::SRC1_ALPHA, GL_SRC1_ALPHA },
{ BlendFactor::INVERSE_SRC1_ALPHA, GL_ONE_MINUS_SRC_ALPHA }
};
}
void glBlender::Enable(BlendFactor srcFactor, BlendFactor dstFactor)
{
glEnable(GL_BLEND);
glBlendFunc(m_FactorMap[srcFactor], m_FactorMap[dstFactor]);
glBlendFunc(m_FactorMap.at(srcFactor), m_FactorMap.at(dstFactor));
}
void glBlender::Disable()

View file

@ -1,8 +1,9 @@
#pragma pnce
#pragma once
#include "Base.h"
#include "Graphics/Blender.h"
#include "Base/Base.h"
namespace Light {
class glBlender : public Blender

View file

@ -5,9 +5,10 @@
namespace Light {
//** CONSTANT_BUFFER **//
//==================== CONSTANT_BUFFER ====================//
glConstantBuffer::glConstantBuffer(ConstantBufferIndex index, unsigned int size)
: m_Index((int)index)
: m_BufferID(NULL),
m_Index(static_cast<int>(index))
{
glCreateBuffers(1, &m_BufferID);
glNamedBufferData(m_BufferID, size, nullptr, GL_DYNAMIC_DRAW);
@ -35,9 +36,11 @@ namespace Light {
{
glUnmapNamedBuffer(m_BufferID);
}
//==================== CONSTANT_BUFFER ====================//
//** VERTEX_BUFFER **//
//==================== VERTEX_BUFFER ====================//
glVertexBuffer::glVertexBuffer(float* vertices, unsigned int count)
: m_BufferID(NULL)
{
glCreateBuffers(1, &m_BufferID);
glNamedBufferData(m_BufferID, count * sizeof(float), vertices, GL_DYNAMIC_DRAW);
@ -48,16 +51,6 @@ namespace Light {
glDeleteBuffers(1, &m_BufferID);
}
void* glVertexBuffer::Map()
{
return glMapNamedBuffer(m_BufferID, GL_WRITE_ONLY);
}
void glVertexBuffer::UnMap()
{
glUnmapNamedBuffer(m_BufferID);
}
void glVertexBuffer::Bind()
{
glBindBuffer(GL_ARRAY_BUFFER, m_BufferID);
@ -68,8 +61,20 @@ namespace Light {
glBindBuffer(GL_ARRAY_BUFFER, NULL);
}
//** INDEX_BUFFER **//
void* glVertexBuffer::Map()
{
return glMapNamedBuffer(m_BufferID, GL_WRITE_ONLY);
}
void glVertexBuffer::UnMap()
{
glUnmapNamedBuffer(m_BufferID);
}
//==================== VERTEX_BUFFER ====================//
//==================== INDEX_BUFFER ====================//
glIndexBuffer::glIndexBuffer(unsigned int* indices, unsigned int count)
: m_BufferID(NULL)
{
// generate indices if not provided
bool hasIndices = !!indices;
@ -85,18 +90,18 @@ namespace Light {
// create indices
indices = new unsigned int[count];
unsigned int offset = 0;
for (unsigned int i = 0; i < count; i += 6)
unsigned int offset = 0u;
for (unsigned int i = 0u; i < count; i += 6u)
{
indices[i + 0] = offset + 0;
indices[i + 1] = offset + 1;
indices[i + 2] = offset + 2;
indices[i + 0] = offset + 0u;
indices[i + 1] = offset + 1u;
indices[i + 2] = offset + 2u;
indices[i + 3] = offset + 2;
indices[i + 4] = offset + 3;
indices[i + 5] = offset + 0;
indices[i + 3] = offset + 2u;
indices[i + 4] = offset + 3u;
indices[i + 5] = offset + 0u;
offset += 4;
offset += 4u;
}
}
@ -123,5 +128,6 @@ namespace Light {
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, NULL);
}
//==================== INDEX_BUFFER ====================//
}

View file

@ -1,14 +1,17 @@
#pragma once
#include "Base.h"
#include "Graphics/Buffers.h"
#include "Base/Base.h"
namespace Light {
//========== CONSTANT_BUFFER ==========//
class glConstantBuffer : public ConstantBuffer
{
private:
unsigned int m_BufferID, m_Index;
unsigned int m_BufferID;
unsigned int m_Index;
public:
glConstantBuffer(ConstantBufferIndex index, unsigned int size);
@ -20,7 +23,7 @@ namespace Light {
void UnMap() override;
};
//** VERTEX_BUFFER **//
//========== VERTEX_BUFFER ==========//
class glVertexBuffer : public VertexBuffer
{
private:
@ -30,14 +33,14 @@ namespace Light {
glVertexBuffer(float* vertices, unsigned int count);
~glVertexBuffer();
void* Map() override;
void UnMap() override;
void Bind() override;
void UnBind() override;
void* Map() override;
void UnMap() override;
};
//** INDEX_BUFFER **//
//========== INDEX_BUFFER ==========//
class glIndexBuffer : public IndexBuffer
{
private:

View file

@ -1,14 +1,17 @@
#include "ltpch.h"
#include "glFramebuffer.h"
#include <glm/glm.hpp>
#include <glad/glad.h>
#include <glm/glm.hpp>
namespace Light {
glFramebuffer::glFramebuffer(const FramebufferSpecification& specification)
: m_Specification(specification), m_BufferID(0u), m_ColorAttachment(0u), m_DepthStencilAttachment(0u)
: m_Specification(specification),
m_BufferID(NULL),
m_ColorAttachmentID(NULL),
m_DepthStencilAttachmentID(NULL)
{
Resize({ specification.width, specification.height });
}
@ -16,12 +19,13 @@ namespace Light {
glFramebuffer::~glFramebuffer()
{
glDeleteFramebuffers(1, &m_BufferID);
glDeleteTextures(1, &m_ColorAttachment);
// glDeleteTextures(1, &m_DepthStencilAttachment);
glDeleteTextures(1, &m_ColorAttachmentID);
// glDeleteTextures(1, &m_DepthStencilAttachmentID);
}
void glFramebuffer::BindAsTarget()
{
// #todo: use viewport instead of default x=0, y=0
glBindFramebuffer(GL_FRAMEBUFFER, m_BufferID);
glViewport(0, 0, m_Specification.width, m_Specification.height);
@ -34,33 +38,36 @@ namespace Light {
LT_ENGINE_ERROR("glFramebuffer::BindAsResource: NO_IMPLEMENT!");
}
void glFramebuffer::Resize(const glm::vec2& size)
void glFramebuffer::Resize(const glm::uvec2& size)
{
if (m_BufferID)
{
glDeleteFramebuffers(1, &m_BufferID);
glDeleteTextures(1, &m_ColorAttachment);
// glDeleteTextures(1, &m_DepthStencilAttachment);
glDeleteTextures(1, &m_ColorAttachmentID);
// glDeleteTextures(1, &m_DepthStencilAttachmentID);
}
m_Specification.width = std::clamp(size.x, 1u, (unsigned int)GL_MAX_TEXTURE_SIZE);
m_Specification.height = std::clamp(size.y, 1u, (unsigned int)GL_MAX_TEXTURE_SIZE);
glCreateFramebuffers(1, &m_BufferID);
glBindFramebuffer(GL_FRAMEBUFFER, m_BufferID);
// create color attachment
glCreateTextures(GL_TEXTURE_2D, 1, &m_ColorAttachment);
glBindTexture(GL_TEXTURE_2D, m_ColorAttachment);
glCreateTextures(GL_TEXTURE_2D, 1, &m_ColorAttachmentID);
glBindTexture(GL_TEXTURE_2D, m_ColorAttachmentID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Specification.width, m_Specification.height, NULL, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTextureParameteri(m_ColorAttachment, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(m_ColorAttachment, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_ColorAttachment, 0);
glTextureParameteri(m_ColorAttachmentID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(m_ColorAttachmentID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_ColorAttachmentID, 0);
// glTextureStorage2D(m_ColorAttachment, 0, GL_RGBA8, m_Specification.width, m_Specification.height);
// glTextureStorage2D(m_ColorAttachmentID, 0, GL_RGBA8, m_Specification.width, m_Specification.height);
// glCreateTextures(GL_TEXTURE_2D, 1, &m_DepthStencilAttachment);
// glBindTexture(GL_TEXTURE_2D, m_DepthStencilAttachment);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, m_Specification.width, m_Specification.height, NULL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr);
// // glTextureStorage2D(m_DepthStencilAttachment, 0, GL_DEPTH24_STENCIL8, m_Specification.width, m_Specification.height);
// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthStencilAttachment, 0);
// glCreateTextures(GL_TEXTURE_2D, 1, &m_DepthStencilAttachmentID);
// glBindTexture(GL_TEXTURE_2D, m_DepthStencilAttachmentID);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, m_Specification.width, m_Specification.height, NULL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr);
// // glTextureStorage2D(m_DepthStencilAttachmentID, 0, GL_DEPTH24_STENCIL8, m_Specification.width, m_Specification.height);
// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthStencilAttachmentID, 0);
LT_ENGINE_ASSERT((glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE), "glFramebuffer::Validate: framebuffer is incomplete");

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/Framebuffer.h"
#include "Base/Base.h"
namespace Light {
class glFramebuffer : public Framebuffer
@ -10,18 +11,19 @@ namespace Light {
private:
FramebufferSpecification m_Specification;
unsigned int m_BufferID, m_ColorAttachment, m_DepthStencilAttachment;
unsigned int m_BufferID;
unsigned int m_ColorAttachmentID, m_DepthStencilAttachmentID;
public:
glFramebuffer(const FramebufferSpecification& specification);
~glFramebuffer();
inline void* GetColorAttachment() override { return (void*)m_ColorAttachment; }
void BindAsTarget() override;
void BindAsResource() override;
void Resize(const glm::vec2& size) override;
void Resize(const glm::uvec2& size) override;
inline void* GetColorAttachment() override { return (void*)m_ColorAttachmentID; }
};
}

View file

@ -3,11 +3,14 @@
#include "Events/WindowEvents.h"
// forward declaration
#include "Graphics/Renderer.h"
#include "Graphics/RenderCommand.h"
#include "UserInterface/UserInterface.h"
#include "Utility/ResourceManager.h"
#include "Graphics/Blender.h" // required for forward declaration
#include "Graphics/Buffers.h" // required for forward declaration
#include "Graphics/Renderer.h" // required for forward declaration
#include "Graphics/RenderCommand.h" // required for forward declaration
#include "UserInterface/UserInterface.h" // required for forward declaration
#include "Utility/ResourceManager.h" // required for forward declaration
#include <glad/glad.h>
#include <GLFW/glfw3.h>
@ -50,11 +53,12 @@ namespace Light {
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, 0, nullptr, GL_TRUE);
#else // LT_DIST
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, 0, nullptr, GL_TRUE);
#else // LIGHT_DIST
return;
#endif
// setup message callback
/* setup message callback */
glDebugMessageCallback([](unsigned int source, unsigned int type,
unsigned int id, unsigned int severity,
int length, const char* message,

View file

@ -1,14 +1,13 @@
#pragma once
#include "Base.h"
#include "Graphics/GraphicsContext.h"
#include "Base/Base.h"
struct GLFWwindow;
namespace Light {
class WindowResizedEvent;
class glGraphicsContext : public GraphicsContext
{
private:
@ -17,7 +16,7 @@ namespace Light {
public:
glGraphicsContext(GLFWwindow* windowHandle);
virtual void LogDebugData() override;
void LogDebugData() override;
private:
void SetDebugMessageCallback();

View file

@ -8,7 +8,8 @@ namespace Light {
glRenderCommand::glRenderCommand(GLFWwindow* windowHandle)
: m_WindowHandle(windowHandle)
{ }
{
}
void glRenderCommand::SwapBuffers()
{

View file

@ -1,8 +1,11 @@
#pragma once
#include "Base.h"
#include "Graphics/RenderCommand.h"
#include "Base/Base.h"
struct GLFWwindow;
namespace Light {
class glRenderCommand : public RenderCommand
@ -19,9 +22,9 @@ namespace Light {
void Draw(unsigned int count) override;
void DrawIndexed(unsigned int count) override;
virtual void DefaultTargetFramebuffer() override;
void DefaultTargetFramebuffer() override;
virtual void SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) override;
void SetViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) override;
};
}

View file

@ -10,6 +10,7 @@
namespace Light {
glShader::glShader(const std::string& vertexSource, const std::string& fragmentSource)
: m_ShaderID(NULL)
{
m_ShaderID = glCreateProgram();
@ -29,7 +30,7 @@ namespace Light {
glCompileShader(vertexShader);
glCompileShader(fragmentShader);
//** #TEMP_HANDLE_SHADER_COMPILE_FAILURE# **//
/* #TEMP_HANDLE_SHADER_COMPILE_FAILURE# */
int isCompiled = 0;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
@ -64,7 +65,7 @@ namespace Light {
return;
}
//** #TEMP_HANDLE_SHADER_COMPILE_FAILURE# **//
/* #TEMP_HANDLE_SHADER_COMPILE_FAILURE# */
// attach shaders
glAttachShader(m_ShaderID, vertexShader);
@ -93,14 +94,4 @@ namespace Light {
glUseProgram(NULL);
}
void glShader::SetUniformMat4(const std::string& name, const glm::mat4& value)
{
int location = glGetUniformLocation(m_ShaderID, name.c_str());
if (location == -1)
LT_ENGINE_ERROR("glShader::SetUniformMat4: failed to find uniform: {}", name);
glUniformMatrix4fv(location, 1, GL_FALSE, &(value[0][0]));
}
}

View file

@ -1,9 +1,8 @@
#pragma once
#include "Base.h"
#include "Graphics/Shader.h"
#include <glm/glm.hpp>
#include "Base/Base.h"
namespace Light {
@ -18,8 +17,6 @@ namespace Light {
void Bind() override;
void UnBind() override;
void SetUniformMat4(const std::string& name, const glm::mat4& value) override;
};
}

View file

@ -1,9 +1,13 @@
#pragma once
#include "Base.h"
#include "Graphics/SharedContext.h"
#include "Base/Base.h"
namespace Light {
struct glSharedContext { };
class glSharedContext : public SharedContext
{
};
}

View file

@ -6,6 +6,7 @@
namespace Light {
glTexture::glTexture(unsigned int width, unsigned int height, unsigned int components, unsigned char* pixels)
: m_TextureID(NULL)
{
// create texture
glCreateTextures(GL_TEXTURE_2D, 1, &m_TextureID);

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Graphics/Texture.h"
#include "Base/Base.h"
namespace Light {
class glTexture : public Texture

View file

@ -1,12 +1,13 @@
#include "ltpch.h"

#include "ltpch.h"
#include "glUserInterface.h"
#include <GLFW/glfw3.h>
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <GLFW/glfw3.h>
namespace Light {
glUserInterface::glUserInterface(GLFWwindow* windowHandle)
@ -58,7 +59,7 @@ namespace Light {
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
//** #TEMP_IMGUI_DEMO_TEMP# **//
/* #TEMP_IMGUI_DEMO_TEMP# */
ImGui::ShowDemoWindow();
}

View file

@ -1,9 +1,10 @@
#pragma once
#include "Base.h"
#include "UserInterface/UserInterface.h"
class GLFWwindow;
#include "Base/Base.h"
struct GLFWwindow;
namespace Light {

View file

@ -8,6 +8,7 @@
namespace Light {
glVertexLayout::glVertexLayout(Ref<VertexBuffer> buffer, const std::vector<std::pair<std::string, VertexElementType>>& elements)
: m_ArrayID(NULL)
{
// check
LT_ENGINE_ASSERT(std::dynamic_pointer_cast<glVertexBuffer>(buffer), "glVertexLayout::glVertexLayout: failed to cast 'VertexBuffer' to 'glVertexBuffer'");

View file

@ -1,10 +1,13 @@
#pragma once
#include "Base.h"
#include "Graphics/VertexLayout.h"
#include "Base/Base.h"
namespace Light {
class VertexBuffer;
struct glVertexElementDesc
{
unsigned int type;

View file

@ -18,7 +18,8 @@ namespace Light {
}
lWindow::lWindow(std::function<void(Event&)> callback)
: m_EventCallback(callback)
: m_Handle(nullptr),
m_EventCallback(callback)
{
// init glfw
LT_ENGINE_ASSERT(glfwInit(), "lWindow::lWindow: failed to initialize 'glfw'");
@ -32,11 +33,11 @@ namespace Light {
m_Handle = glfwCreateWindow(1u, 1u, "", nullptr, nullptr);
LT_ENGINE_ASSERT(m_Handle, "lWindow::lWindow: failed to create 'GLFWwindow'");
// manage events
// bind event stuff
glfwSetWindowUserPointer(m_Handle, &m_EventCallback);
BindGlfwEvents();
// create graphics contextG
// create graphics context
m_GraphicsContext = GraphicsContext::Create(GraphicsAPI::OpenGL, m_Handle);
LT_ENGINE_ASSERT(m_GraphicsContext, "lWindow::lWindow: failed to create 'GraphicsContext'");
}
@ -55,12 +56,12 @@ namespace Light {
{
switch (event.GetEventType())
{
// closed
/* closed */
case EventType::WindowClosed:
b_Closed = true;
break;
// resized
/* resized */
case EventType::WindowResized:
OnWindowResize((const WindowResizedEvent&)event);
break;
@ -72,10 +73,10 @@ namespace Light {
m_Properties.size = event.GetSize();
}
void lWindow::SetProperties(const WindowProperties& properties, bool affectsVisiblity /* = false */)
void lWindow::SetProperties(const WindowProperties& properties, bool overrideVisibility /* = false */)
{
// save the visibility status and re-assign if 'affectVisibility' is false
bool visible = affectsVisiblity ? properties.visible : m_Properties.visible;
// save the visibility status and re-assign if 'overrideVisibility' is false
bool visible = overrideVisibility ? properties.visible : m_Properties.visible;
m_Properties = properties;
m_Properties.visible = visible;
@ -121,8 +122,8 @@ namespace Light {
void lWindow::BindGlfwEvents()
{
//** MOUSE_EVENTS **//
// cursor position
//============================== MOUSE_EVENTS ==============================//
/* cursor position */
glfwSetCursorPosCallback(m_Handle, [](GLFWwindow* window, double xpos, double ypos)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -131,7 +132,7 @@ namespace Light {
callback(event);
});
// button
/* mouse button */
glfwSetMouseButtonCallback(m_Handle, [](GLFWwindow* window, int button, int action, int mods)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -148,7 +149,7 @@ namespace Light {
}
});
// scroll
/* scroll */
glfwSetScrollCallback(m_Handle, [](GLFWwindow* window, double xoffset, double yoffset)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -156,9 +157,10 @@ namespace Light {
WheelScrolledEvent event(yoffset);
callback(event);
});
//** KEYBOARD_EVENTS **//
// key
//============================== MOUSE_EVENTS ==============================//
//============================== KEYBOARD_EVENTS ==============================//
/* key */
glfwSetKeyCallback(m_Handle, [](GLFWwindow* window, int key, int scancode, int action, int mods)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -174,9 +176,10 @@ namespace Light {
callback(event);
}
});
//** WINDOW_EVENTS **//
// position
//============================== KEYBOARD_EVENTS ==============================//
//============================== WINDOW_EVENTS ==============================//
/* window position */
glfwSetWindowPosCallback(m_Handle, [](GLFWwindow* window, int xpos, int ypos)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -185,8 +188,8 @@ namespace Light {
callback(event);
});
// size
glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow* window, int width, int height)
/* window size */
glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow* window, int width, int height)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
WindowResizedEvent event(width, height);
@ -194,7 +197,7 @@ namespace Light {
callback(event);
});
// close
/* window close */
glfwSetWindowCloseCallback(m_Handle, [](GLFWwindow* window)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -203,7 +206,7 @@ namespace Light {
callback(event);
});
// focus
/* window focus */
glfwSetWindowFocusCallback(m_Handle, [](GLFWwindow* window, int focus)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -219,6 +222,7 @@ namespace Light {
callback(event);
}
});
//============================== WINDOW_EVENTS ==============================//
}
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Core/Window.h"
#include "Base/Base.h"
struct GLFWwindow;
namespace Light {
@ -13,19 +14,20 @@ namespace Light {
class lWindow : public Window
{
private:
GLFWwindow* m_Handle = nullptr;
GLFWwindow* m_Handle;
std::function<void(Event&)> m_EventCallback;
public:
lWindow(std::function<void(Event&)> callback);
~lWindow();
/* events */
void PollEvents() override;
void OnEvent(const Event& event) override;
void SetProperties(const WindowProperties& properties, bool affectsVisiblity = false) override;
//======================================== SETTERS ========================================//
void SetProperties(const WindowProperties& properties, bool overrideVisibility = false) override;
void SetTitle(const std::string& title) override;
@ -33,11 +35,12 @@ namespace Light {
void SetVSync(bool vsync, bool toggle = false) override;
void SetVisibility(bool visible, bool toggle = false);
private:
void BindGlfwEvents();
//======================================== SETTERS ========================================//
private:
void OnWindowResize(const WindowResizedEvent& event);
void BindGlfwEvents();
};
}

View file

@ -18,7 +18,8 @@ namespace Light {
}
wWindow::wWindow(std::function<void(Event&)> callback)
: m_EventCallback(callback)
: m_Handle(nullptr),
m_EventCallback(callback)
{
// init glfw
LT_ENGINE_ASSERT(glfwInit(), "wWindow::wWindow: failed to initialize 'glfw'");
@ -46,10 +47,36 @@ namespace Light {
glfwDestroyWindow(m_Handle);
}
void wWindow::SetProperties(const WindowProperties& properties, bool affectVisibility /* = false */)
void wWindow::PollEvents()
{
// save the visibility status and re-assign if 'affectVisibility' is false
bool visible = affectVisibility ? properties.visible : m_Properties.visible;
glfwPollEvents();
}
void wWindow::OnEvent(const Event& event)
{
switch (event.GetEventType())
{
/* closed */
case EventType::WindowClosed:
b_Closed = true;
break;
/* resized */
case EventType::WindowResized:
OnWindowResize((const WindowResizedEvent&)event);
break;
}
}
void wWindow::OnWindowResize(const WindowResizedEvent& event)
{
m_Properties.size = event.GetSize();
}
void wWindow::SetProperties(const WindowProperties& properties, bool overrideVisiblity /* = false */)
{
// save the visibility status and re-assign if 'overrideVisibility' is false
bool visible = overrideVisiblity ? properties.visible : m_Properties.visible;
m_Properties = properties;
m_Properties.visible = visible;
@ -60,6 +87,29 @@ namespace Light {
SetVisibility(visible);
}
void wWindow::SetTitle(const std::string& title)
{
m_Properties.title = title;
glfwSetWindowTitle(m_Handle, m_Properties.title.c_str());
}
void wWindow::SetSize(const glm::uvec2& size, bool additive /* = false */)
{
m_Properties.size.x = size.x == 0u ? m_Properties.size.x : additive ? m_Properties.size.x + size.x : size.x;
m_Properties.size.y = size.y == 0u ? m_Properties.size.y : additive ? m_Properties.size.y + size.y : size.y;
glfwSetWindowSize(m_Handle, size.x, size.y);
}
void wWindow::SetVSync(bool vsync, bool toggle /* = false */)
{
m_Properties.vsync = toggle ? !m_Properties.vsync : vsync;
glfwSwapInterval(m_Properties.vsync);
}
void wWindow::SetVisibility(bool visible, bool toggle)
{
m_Properties.visible = toggle ? !m_Properties.visible : visible;
@ -70,63 +120,17 @@ namespace Light {
glfwHideWindow(m_Handle);
}
void wWindow::PollEvents()
{
glfwPollEvents();
}
void wWindow::OnEvent(const Event& event)
{
switch (event.GetEventType())
{
// closed
case EventType::WindowClosed:
b_Closed = true;
break;
// resized
case EventType::WindowResized:
OnWindowResize((const WindowResizedEvent&)event);
break;
}
}
void wWindow::OnWindowResize(const WindowResizedEvent& event)
{
m_Properties.size = event.GetSize();
}
void wWindow::SetTitle(const std::string& title)
{
m_Properties.title = title;
glfwSetWindowTitle(m_Handle, m_Properties.title.c_str());
}
void wWindow::SetVSync(bool vsync, bool toggle /* = false */)
{
m_Properties.vsync = toggle ? !m_Properties.vsync : vsync;
glfwSwapInterval(m_Properties.vsync);
}
void wWindow::SetSize(const glm::uvec2& size, bool additive /* = false */)
{
glfwSetWindowSize(m_Handle, size.x == 0u ? m_Properties.size.x : additive ? m_Properties.size.x + size.x : size.x,
size.y == 0u ? m_Properties.size.y : additive ? m_Properties.size.y + size.y : size.y);
}
void wWindow::BindGlfwEvents()
{
//** MOUSE_EVENTS **//
// cursor position
//============================== MOUSE_EVENTS ==============================//
/* cursor position */
glfwSetCursorPosCallback(m_Handle, [](GLFWwindow* window, double xpos, double ypos)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
callback(MouseMovedEvent(xpos, ypos));
});
// button
/* mouse button */
glfwSetMouseButtonCallback(m_Handle, [](GLFWwindow* window, int button, int action, int mods)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -137,15 +141,16 @@ namespace Light {
callback(ButtonReleasedEvent (button));
});
// scroll
/* scroll */
glfwSetScrollCallback(m_Handle, [](GLFWwindow* window, double xoffset, double yoffset)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
callback(WheelScrolledEvent (yoffset));
});
//============================== MOUSE_EVENTS ==============================//
//** KEYBOARD_EVENTS **//
// key
//============================== KEYBOARD_EVENTS ==============================//
/* key */
glfwSetKeyCallback(m_Handle, [](GLFWwindow* window, int key, int scancode, int action, int mods)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -155,30 +160,31 @@ namespace Light {
else if(action == GLFW_RELEASE)
callback(KeyReleasedEvent(key));
});
//============================== KEYBOARD_EVENTS ==============================//
// Window Events //
// position
//============================== WINDOW_EVENTS ==============================//
/* window position */
glfwSetWindowPosCallback(m_Handle, [](GLFWwindow* window, int xpos, int ypos)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
callback(WindowMovedEvent(xpos, ypos));
});
// size
/* window size */
glfwSetWindowSizeCallback(m_Handle, [](GLFWwindow* window, int width, int height)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
callback(WindowResizedEvent(width, height));
});
// close
/* window close */
glfwSetWindowCloseCallback(m_Handle, [](GLFWwindow* window)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
callback(WindowClosedEvent());
});
// focus
/* window focus */
glfwSetWindowFocusCallback(m_Handle, [](GLFWwindow* window, int focus)
{
std::function<void(Event&)> callback = *(std::function<void(Event&)>*)glfwGetWindowUserPointer(window);
@ -188,5 +194,6 @@ namespace Light {
else
callback(WindowLostFocusEvent());
});
//============================== WINDOW_EVENTS ==============================//
}
}

View file

@ -1,8 +1,9 @@
#pragma once
#include "Base.h"
#include "Core/Window.h"
#include "Base/Base.h"
struct GLFWwindow;
namespace Light {
@ -13,20 +14,20 @@ namespace Light {
class wWindow : public Window
{
private:
GLFWwindow* m_Handle = nullptr;
GLFWwindow* m_Handle;
std::function<void(Event&)> m_EventCallback;
public:
wWindow(std::function<void(Event&)> callback);
~wWindow();
/* events */
void PollEvents() override;
void OnEvent(const Event& event) override;
//** SETTERS **//
void SetProperties(const WindowProperties& properties, bool affectVisibility = false) override;
//======================================== SETTERS ========================================//
void SetProperties(const WindowProperties& properties, bool overrideVisibility = false) override;
void SetTitle(const std::string& title) override;
@ -34,11 +35,12 @@ namespace Light {
void SetVSync(bool vsync, bool toggle = false) override;
void SetVisibility(bool visible, bool toggle = false) override;
//======================================== SETTERS ========================================//
private:
void BindGlfwEvents();
void OnWindowResize(const WindowResizedEvent& event);
void BindGlfwEvents();
};
}

View file

@ -1,6 +1,5 @@
#define LIGHT_ENTRY_POINT
#include <LightEngine.h>
#include <EntryPoint.h>
#include "MirrorLayer.h"
@ -31,7 +30,7 @@ namespace Light {
}
};
::Light::Application* ::Light::CreateApplication()
Application* CreateApplication()
{
return new Mirror();
}

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