Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b4a891a58 | ||
|
|
6c71bd46af | ||
|
|
b593b7e083 | ||
|
|
a927b96a99 | ||
|
|
126862748e |
@@ -6,4 +6,3 @@ docs/*
|
|||||||
!docs/CMake*
|
!docs/CMake*
|
||||||
!docs/Doxyfile.in
|
!docs/Doxyfile.in
|
||||||
!.clangd
|
!.clangd
|
||||||
.glsld
|
|
||||||
+12
-64
@@ -7,10 +7,6 @@ set(CMAKE_CXX_STANDARD 17)
|
|||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||||
|
|
||||||
include(GNUInstallDirs)
|
|
||||||
include(CMakePackageConfigHelpers)
|
|
||||||
include(CMakeDependentOption)
|
|
||||||
|
|
||||||
function(toAbsolutePath SETVAR PATHS)
|
function(toAbsolutePath SETVAR PATHS)
|
||||||
set(PATHS ${PATHS} ${ARGN})
|
set(PATHS ${PATHS} ${ARGN})
|
||||||
set(RET_VAL "")
|
set(RET_VAL "")
|
||||||
@@ -32,42 +28,12 @@ if(CMAKE_BUILD_TYPE STREQUAL "Release")
|
|||||||
message(STATUS "Targeting Release build")
|
message(STATUS "Targeting Release build")
|
||||||
elseif(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
elseif(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||||
message(STATUS "Targeting Debug build")
|
message(STATUS "Targeting Debug build")
|
||||||
set(NB_DEBUG_BUILD ON)
|
set(NB_LOGGING ON)
|
||||||
|
set(NB_BUILD_TESTS ON)
|
||||||
|
set(NB_BUILD_DOCS ON)
|
||||||
add_compile_definitions(_NB_BUILD_DEBUG)
|
add_compile_definitions(_NB_BUILD_DEBUG)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
cmake_dependent_option(NB_LOGGING
|
|
||||||
"Creates a default logger and automatically logs with code locations."
|
|
||||||
ON
|
|
||||||
NB_DEBUG_BUILD
|
|
||||||
OFF
|
|
||||||
)
|
|
||||||
cmake_dependent_option(NB_BUILD_TESTS
|
|
||||||
"Build unit tests"
|
|
||||||
ON
|
|
||||||
NB_DEBUG_BUILD
|
|
||||||
OFF
|
|
||||||
)
|
|
||||||
cmake_dependent_option(NB_BUILD_DOCS
|
|
||||||
"Build documentation"
|
|
||||||
ON
|
|
||||||
NB_DEBUG_BUILD
|
|
||||||
OFF
|
|
||||||
)
|
|
||||||
cmake_dependent_option(NBENGINE_INSTALL
|
|
||||||
"Install NBEngine"
|
|
||||||
ON
|
|
||||||
NB_DEBUG_BUILD
|
|
||||||
OFF
|
|
||||||
)
|
|
||||||
cmake_dependent_option(NB_MONITOR_OPENGL_CALLS
|
|
||||||
"Monitors every OpenGL call for errors"
|
|
||||||
ON
|
|
||||||
NB_DEBUG_BUILD
|
|
||||||
OFF
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
|
||||||
message(STATUS "Building for Windows")
|
message(STATUS "Building for Windows")
|
||||||
set(NB_TARGET_WINDOWS ON)
|
set(NB_TARGET_WINDOWS ON)
|
||||||
@@ -89,24 +55,27 @@ if(NB_BUILD_TESTS)
|
|||||||
FetchContent_MakeAvailable(gtest)
|
FetchContent_MakeAvailable(gtest)
|
||||||
endif()
|
endif()
|
||||||
set(GTEST_COLOR ON)
|
set(GTEST_COLOR ON)
|
||||||
|
set(GLFW_BUILD_TESTS ON CACHE BOOL "" FORCE)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if (NB_LOGGING)
|
if (NB_LOGGING)
|
||||||
message(STATUS "Building with automatic logging")
|
message(STATUS "Building with automatic logging")
|
||||||
add_compile_definitions(_NB_AUTOLOG)
|
add_compile_definitions(_NB_AUTOLOG)
|
||||||
add_compile_definitions(_NB_CODE_ERROR_LOCATIONS)
|
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(NB_TARGET_WINDOWS)
|
if (NB_TARGET_WINDOWS)
|
||||||
add_compile_definitions(_NB_TARGET_WINDOWS)
|
add_compile_definitions(_NB_TARGET_WINDOWS)
|
||||||
endif()
|
elseif (NB_TARGET_LINUX)
|
||||||
if(NB_TARGET_LINUX)
|
|
||||||
add_compile_definitions(_NB_TARGET_LINUX)
|
add_compile_definitions(_NB_TARGET_LINUX)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
get_filename_component(NBENGINE_ROOT ${CMAKE_CURRENT_LIST_DIR} ABSOLUTE)
|
# External Dep paths
|
||||||
|
set(GLFW_PATH ../glfw/)
|
||||||
|
set(GLAD_PATH ../glad/)
|
||||||
|
get_filename_component(GLFW_PATH ${GLFW_PATH} ABSOLUTE)
|
||||||
|
get_filename_component(GLAD_PATH ${GLAD_PATH} ABSOLUTE)
|
||||||
|
|
||||||
add_subdirectory(./engine ${PROJECT_BINARY_DIR}/${CMAKE_BUILD_TYPE})
|
add_subdirectory(./engine)
|
||||||
|
|
||||||
# Toggle
|
# Toggle
|
||||||
set(NB_REBUILD_DOCS)
|
set(NB_REBUILD_DOCS)
|
||||||
@@ -114,24 +83,3 @@ set(NB_REBUILD_DOCS)
|
|||||||
if (NB_BUILD_DOCS)
|
if (NB_BUILD_DOCS)
|
||||||
add_subdirectory(./docs)
|
add_subdirectory(./docs)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
include(CMakePackageConfigHelpers)
|
|
||||||
configure_package_config_file(
|
|
||||||
"NBEngineConfig.cmake.in"
|
|
||||||
"${PROJECT_BINARY_DIR}/cmake/NBEngineConfig.cmake"
|
|
||||||
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
|
|
||||||
PATH_VARS CMAKE_INSTALL_LIBDIR
|
|
||||||
)
|
|
||||||
write_basic_package_version_file(
|
|
||||||
"${PROJECT_BINARY_DIR}/cmake/NBEngineConfigVersion.cmake"
|
|
||||||
COMPATIBILITY AnyNewerVersion
|
|
||||||
)
|
|
||||||
|
|
||||||
if (NBENGINE_INSTALL)
|
|
||||||
include(GNUInstallDirs)
|
|
||||||
install(FILES
|
|
||||||
"${PROJECT_BINARY_DIR}/cmake/NBEngineConfig.cmake"
|
|
||||||
"${PROJECT_BINARY_DIR}/cmake/NBEngineConfigVersion.cmake"
|
|
||||||
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
@PACKAGE_INIT@
|
|
||||||
set(NBENGINE_PACKAGES
|
|
||||||
NBCore
|
|
||||||
NBGraphics
|
|
||||||
)
|
|
||||||
foreach(NBENGINE_LIB ${NBENGINE_PACKAGES})
|
|
||||||
include("${CMAKE_CURRENT_LIST_DIR}/${NBENGINE_LIB}Config.cmake")
|
|
||||||
endforeach()
|
|
||||||
@@ -1,23 +1,21 @@
|
|||||||
# NBEngine
|
# NBEngine
|
||||||
|
|
||||||
|
My own GUI (and related stuff needed for GUI programs) engine. I suck at coding. Do not judge.
|
||||||
|
|
||||||
## Current Implemented Libraries
|
## Current Implemented Libraries
|
||||||
|
|
||||||
These are subject to (hopefully) grow in size as more stuff gets added.
|
These are subject to (hopefully) grow in size as more stuff gets added.
|
||||||
|
|
||||||
* NBCore: Core/foundational functionality for all other subpackages to be built upon.
|
|
||||||
* Erroring and Logging
|
|
||||||
* Basic data structures and declarations
|
|
||||||
* NBWindow: Creates and manages GLFW windows
|
* NBWindow: Creates and manages GLFW windows
|
||||||
* NBEvents: Multithreading event manager. Very unstable. Sucks a lot.
|
* NBEvents: Multithreading event manager. Very unstable. Sucks a lot.
|
||||||
|
|
||||||
## Dependencies and Foundations
|
## Dependencies and Foundations
|
||||||
|
|
||||||
For Code:
|
While the engine is intended to be a close-to-ground-up project, there's no point in reinventing the spokes that
|
||||||
|
make up a wheel. This project utilizes and depends on (expected to change and grow):
|
||||||
|
|
||||||
* GLFW
|
* GLFW
|
||||||
* Glad
|
* Glad
|
||||||
|
|
||||||
For Repo:
|
Additionally, it's important to note that right now this project is on Windows only. I wanna work on this in Linux soon
|
||||||
|
("soon" whatever that means. Maybe in like 5 years).
|
||||||
* gTest
|
|
||||||
* doxygen
|
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 58 KiB |
+8
-20
@@ -1,30 +1,18 @@
|
|||||||
|
include_directories(./.)
|
||||||
|
|
||||||
add_subdirectory(./NBCore)
|
add_subdirectory(./NBCore)
|
||||||
|
add_subdirectory(./NBEvents)
|
||||||
get_target_property(NBCORE_INTERFACE_INCLUDES NBCore INTERFACE_INCLUDE_DIRECTORIES)
|
|
||||||
include_directories(${NBCORE_INTERFACE_INCLUDES})
|
|
||||||
|
|
||||||
#add_subdirectory(./NBEvents)
|
|
||||||
add_subdirectory(./NBGraphics)
|
add_subdirectory(./NBGraphics)
|
||||||
add_subdirectory(./NBData)
|
|
||||||
|
|
||||||
if (NB_CORE_SOURCE OR NB_EVENTS_SOURCE OR NB_GRAPHICS_SOURCE OR NB_DATA_SOURCE)
|
if (NB_CORE_SOURCE OR NB_EVENTS_SOURCE OR NB_GRAPHICS_SOURCE)
|
||||||
set(NB_SOURCE_FILES "")
|
set(NB_SOURCE_FILES "")
|
||||||
list(APPEND NB_SOURCE_FILES
|
list(APPEND NB_SOURCE_FILES ${NB_CORE_SOURCE} ${NB_GRAPHICS_SOURCE} ${NB_EVENTS_SOURCE})
|
||||||
${NB_CORE_SOURCE}
|
|
||||||
${NB_GRAPHICS_SOURCE}
|
|
||||||
${NB_EVENTS_SOURCE}
|
|
||||||
${NB_DATA_SOURCE}
|
|
||||||
)
|
|
||||||
set(NB_SOURCE_FILES ${NB_SOURCE_FILES} PARENT_SCOPE)
|
set(NB_SOURCE_FILES ${NB_SOURCE_FILES} PARENT_SCOPE)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if (NB_CORE_INCLUDE OR NB_EVENTS_INCLUDE OR NB_GRAPHICS_INCLUDE OR NB_DATA_INCLUDE)
|
|
||||||
|
if (NB_CORE_INCLUDE OR NB_EVENTS_INCLUDE OR NB_GRAPHICS_INCLUDE)
|
||||||
set(NB_INCLUDE_FILES "")
|
set(NB_INCLUDE_FILES "")
|
||||||
list(APPEND NB_INCLUDE_FILES
|
list(APPEND NB_INCLUDE_FILES ${NB_CORE_INCLUDE} ${NB_GRAPHICS_INCLUDE} ${NB_EVENTS_INCLUDE})
|
||||||
${NB_CORE_INCLUDE}
|
|
||||||
${NB_GRAPHICS_INCLUDE}
|
|
||||||
${NB_EVENTS_INCLUDE}
|
|
||||||
${NB_DATA_INCLUDE}
|
|
||||||
)
|
|
||||||
set(NB_INCLUDE_FILES ${NB_INCLUDE_FILES} PARENT_SCOPE)
|
set(NB_INCLUDE_FILES ${NB_INCLUDE_FILES} PARENT_SCOPE)
|
||||||
endif()
|
endif()
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_ANSI_TERM
|
||||||
|
#define _NB_ANSI_TERM
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
/*
|
||||||
|
----------- TECH DEBT ------------
|
||||||
|
Idk wtf to do here. This was originally to allow me to print
|
||||||
|
to terminal easily, but it's becoming too much of an investment.
|
||||||
|
For the time being, drop it.
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
template <typename ST, typename U>
|
||||||
|
struct SmartText {
|
||||||
|
using Type = ST;
|
||||||
|
using ValType = U;
|
||||||
|
static constexpr bool HasChild = Type::HasChild;
|
||||||
|
|
||||||
|
SmartText() = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Type, typename U>
|
||||||
|
struct StyleFormatter : SmartText<StyleFormatter<Type, U>, U> {
|
||||||
|
using Base = SmartText<StyleFormatter<Type, U>, U>;
|
||||||
|
using typename Base::ValType;
|
||||||
|
static constexpr bool HasChild = true;
|
||||||
|
|
||||||
|
StyleFormatter(const std::string& _fmt, const ValType& _val, const std::string& _closing) :
|
||||||
|
fmt{_fmt}, val{_val}, closing{_closing} {}
|
||||||
|
|
||||||
|
std::string fmt;
|
||||||
|
ValType val;
|
||||||
|
std::string closing;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Child>
|
||||||
|
struct StyleFormatter<Child, void> : SmartText<StyleFormatter<Child, void>, void>{
|
||||||
|
using Base = SmartText<StyleFormatter<Child, void>, void>;
|
||||||
|
using Base::ValType;
|
||||||
|
static constexpr bool HasChild = false;
|
||||||
|
|
||||||
|
StyleFormatter(const std::string& _fmt) : fmt{_fmt} {}
|
||||||
|
|
||||||
|
std::string fmt;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename U=void>
|
||||||
|
struct ANSITextColor;
|
||||||
|
|
||||||
|
template <typename U>
|
||||||
|
struct ANSITextColor : StyleFormatter<ANSITextColor<U>, U> {
|
||||||
|
using Base = StyleFormatter<ANSITextColor, U>;
|
||||||
|
using typename Base::ValType;
|
||||||
|
using Base::HasChild;
|
||||||
|
|
||||||
|
template <typename = typename std::enable_if<HasChild, U>::type>
|
||||||
|
ANSITextColor(const U& _val) : Base{"\x1b[39m", _val, "\x1b[39m"} {}
|
||||||
|
template <typename = typename std::enable_if<!HasChild, U>>
|
||||||
|
ANSITextColor() : Base{"\x1b[92m"} {}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct ANSITextColor<std::string> : StyleFormatter<ANSITextColor<std::string>, std::string> {
|
||||||
|
using Base = StyleFormatter<ANSITextColor<std::string>, std::string>;
|
||||||
|
static constexpr bool HasChild = Base::HasChild;
|
||||||
|
|
||||||
|
template <std::size_t N>
|
||||||
|
ANSITextColor(char const(&_val) [N]) : Base{"\x1b[92m", _val, "\x1b[39m"} {}
|
||||||
|
ANSITextColor(const char* _val) : Base{"\x1b[92m", _val, "\x1b[39m"} {}
|
||||||
|
ANSITextColor(const std::string& _val) : Base{"\x1b[92m", _val, "\x1b[39m"} {}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace nb
|
||||||
|
|
||||||
|
template<typename Type, typename U>
|
||||||
|
std::ostream& operator<<(std::ostream& stream, const nb::StyleFormatter<Type, U>& msg) {
|
||||||
|
if (&stream == &std::cout) {
|
||||||
|
stream << msg.fmt;
|
||||||
|
if (msg.HasChild) {
|
||||||
|
stream << msg.val << msg.closing;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (msg.HasChild) { stream << msg.val; }
|
||||||
|
}
|
||||||
|
stream << std::flush;
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* struct CellBase {
|
||||||
|
uint8_t width;
|
||||||
|
uint8_t height;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct Cell : SmartText<Cell<T>, T> {
|
||||||
|
using Base = SmartText<Cell<T>, T>;
|
||||||
|
using typename Base::ValType;
|
||||||
|
using Base::HasChild;
|
||||||
|
|
||||||
|
Cell(const ValType& _val, const uint8_t& w, const uint8_t& h=1)
|
||||||
|
: val(_val), width(w), height(h) {}
|
||||||
|
|
||||||
|
ValType val;
|
||||||
|
uint8_t width;
|
||||||
|
|
||||||
|
uint8_t height;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <>
|
||||||
|
struct Cell<std::string> : SmartText<Cell<std::string>, std::string> {
|
||||||
|
using Base = SmartText<Cell<std::string>, std::string>;
|
||||||
|
using typename Base::ValType;
|
||||||
|
using Base::HasChild;
|
||||||
|
|
||||||
|
template <std::size_t N>
|
||||||
|
Cell( const(&_val) [N], const uint8_t& w, const uint8_t& h=0) : Cell(std::string(_val), w, h) {}
|
||||||
|
Cell(char* _val, const uint8_t& w, const uint8_t& h=0) : Cell(std::string(_val), w, h) {}
|
||||||
|
Cell(const ValType& _val, const uint8_t& w, const uint8_t& h=0)
|
||||||
|
: val(_val), width(w) {
|
||||||
|
unsigned int strsize = _val.size();
|
||||||
|
height = strsize / width;
|
||||||
|
height += (strsize % width) ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
ValType val;
|
||||||
|
uint8_t width;
|
||||||
|
|
||||||
|
uint8_t height;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
std::ostream& operator<<(std::ostream& stream, const Cell<T>& cll) {
|
||||||
|
if (&stream == &std::cout) {
|
||||||
|
stream << "\x1b[s" << cll.val << "\x1b[u\x1b[" << 1+cll.width << "C\x1b[" << 1+cll.height;
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
void ChangeCellHeight(int i, Cell<T>& cll, const unsigned int& h) {
|
||||||
|
if (h < cll.height) { cll.height=h; }
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
void GetTallestCell(int i, Cell<T>& cll, unsigned int& h) {
|
||||||
|
if (cll.height > h) { h = cll.height; }
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Pack>
|
||||||
|
struct TableRow {
|
||||||
|
using RowCells = std::tuple<Cell<Pack>...>;
|
||||||
|
using CellWidths = std::array<int, sizeof...(Pack)>;
|
||||||
|
using DelimiterArray = std::array<std::string, sizeof...(Pack)+1>;
|
||||||
|
|
||||||
|
TableRow(CellWidths&& widths_, DelimiterArray&& delims_, const Pack&... vals_)
|
||||||
|
: widths(widths_), delimiters(delims_), topBorder("") {
|
||||||
|
nb::ForEach(_cells, GetTallestCell, _height);
|
||||||
|
}
|
||||||
|
|
||||||
|
static constexpr int num_columns = sizeof...(Pack);
|
||||||
|
|
||||||
|
int height() const { return height; }
|
||||||
|
inline int height(const unsigned int newh) {
|
||||||
|
nb::ForEach(_cells, ChangeCellHeight, newh);
|
||||||
|
return (_height=newh);
|
||||||
|
}
|
||||||
|
|
||||||
|
const CellWidths widths;
|
||||||
|
const DelimiterArray delimiters;
|
||||||
|
const std::string topBorder;
|
||||||
|
const std::string bottomBorder;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
RowCells _cells;
|
||||||
|
int _height;
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename... Pack>
|
||||||
|
std::ostream& operator<<(std::ostream& stream, const TableRow<Pack...>& row) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename... Pack>
|
||||||
|
class Table {
|
||||||
|
public:
|
||||||
|
Table(const Pack&... _vals) : row(std::array<int, sizeof...(Pack)>(10),
|
||||||
|
std::array<std::string, sizeof...(Pack)>(""), _vals...) {}
|
||||||
|
private:
|
||||||
|
TableRow<Pack...> row;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace nb
|
||||||
|
|
||||||
|
#ifdef _NB_TARGET_WINDOWS
|
||||||
|
template<typename... Types>
|
||||||
|
std::ostream& operator<<(std::ostream& stream, const nb::TableRow<Types...>& row) {
|
||||||
|
using PosType = decltype(stream.tellp());
|
||||||
|
constexpr int num_cells = sizeof...(Types);
|
||||||
|
|
||||||
|
int col_num = 0;
|
||||||
|
int col_start = 0;
|
||||||
|
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
#endif // _NB_TARGET_WINDOWS */
|
||||||
|
|
||||||
|
#endif // _NB_ANSI_TERM
|
||||||
@@ -1,86 +1,29 @@
|
|||||||
cmake_minimum_required(VERSION 3.10)
|
|
||||||
project(NBCore VERSION 0.1)
|
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|
||||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
|
||||||
|
|
||||||
include(GNUInstallDirs)
|
|
||||||
include(CMakePackageConfigHelpers)
|
|
||||||
|
|
||||||
toAbsolutePath(NB_CORE_SOURCE
|
toAbsolutePath(NB_CORE_SOURCE
|
||||||
./src/ErrorsImpl.cpp
|
./src/Errors.cpp
|
||||||
./src/Logger.cpp
|
# ./src/Logger.cpp
|
||||||
./src/Processes.cpp
|
./src/Processes.cpp
|
||||||
./src/StringUtils.cpp
|
|
||||||
./src/TypeTraits.cpp
|
|
||||||
./src/Utils.cpp
|
./src/Utils.cpp
|
||||||
)
|
)
|
||||||
|
|
||||||
toAbsolutePath(NB_CORE_INCLUDE
|
toAbsolutePath(NB_CORE_INCLUDE
|
||||||
./include/NBCore/DataSink.hpp
|
./ANSITerm.hpp
|
||||||
./include/NBCore/Errors.hpp
|
./DataSink.hpp
|
||||||
./include/NBCore/ErrorsImpl.hpp
|
./Errors.hpp
|
||||||
./include/NBCore/Logger.hpp
|
./Logger.hpp
|
||||||
./include/NBCore/Printer.hpp
|
./Processes.hpp
|
||||||
./include/NBCore/Processes.hpp
|
./ThreadsafeQueue.hpp
|
||||||
./include/NBCore/StringUtils.hpp
|
./Types.hpp
|
||||||
./include/NBCore/ThreadsafeQueue.hpp
|
./TypeTraits.hpp
|
||||||
./include/NBCore/Types.hpp
|
./Utils.hpp
|
||||||
./include/NBCore/TypeTraits.hpp
|
|
||||||
./include/NBCore/Utils.hpp
|
|
||||||
)
|
)
|
||||||
|
|
||||||
set(NB_CORE_SOURCE ${NB_CORE_SOURCE} PARENT_SCOPE)
|
set(NB_CORE_SOURCE ${NB_CORE_SOURCE} PARENT_SCOPE)
|
||||||
set(NB_CORE_INCLUDE ${NB_CORE_INCLUDE} PARENT_SCOPE)
|
set(NB_CORE_INCLUDE ${NB_CORE_INCLUDE} PARENT_SCOPE)
|
||||||
|
|
||||||
add_library(NBCore ${NB_CORE_SOURCE})
|
add_library(NBCore ${NB_CORE_SOURCE})
|
||||||
add_library(NBEngine::Core ALIAS NBCore)
|
|
||||||
target_include_directories(NBCore
|
|
||||||
PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
|
|
||||||
PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
|
|
||||||
)
|
|
||||||
export(
|
|
||||||
TARGETS NBCore
|
|
||||||
FILE "${CMAKE_BINARY_DIR}/cmake/NBCoreTargets.cmake"
|
|
||||||
NAMESPACE NBEngine::
|
|
||||||
)
|
|
||||||
configure_package_config_file(
|
|
||||||
"NBCoreConfig.cmake.in"
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBCoreConfig.cmake"
|
|
||||||
INSTALL_DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
|
|
||||||
PATH_VARS CMAKE_INSTALL_LIBDIR
|
|
||||||
)
|
|
||||||
write_basic_package_version_file(
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBCoreConfigVersion.cmake"
|
|
||||||
COMPATIBILITY AnyNewerVersion
|
|
||||||
)
|
|
||||||
|
|
||||||
if (NBENGINE_INSTALL)
|
target_include_directories(NBCore PUBLIC ./.)
|
||||||
message("Installing NBCore to ${CMAKE_INSTALL_PREFIX}")
|
|
||||||
install(
|
|
||||||
TARGETS NBCore
|
|
||||||
EXPORT NBCoreTargets
|
|
||||||
LIBRARY DESTINATION lib
|
|
||||||
ARCHIVE DESTINATION lib
|
|
||||||
INCLUDES DESTINATION include
|
|
||||||
)
|
|
||||||
install(
|
|
||||||
DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/NBCore"
|
|
||||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
|
|
||||||
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
|
|
||||||
)
|
|
||||||
install(
|
|
||||||
EXPORT NBCoreTargets
|
|
||||||
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
|
|
||||||
NAMESPACE NBEngine::
|
|
||||||
)
|
|
||||||
install(FILES
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBCoreConfig.cmake"
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBCoreConfigVersion.cmake"
|
|
||||||
DESTINATION "${CMAKE_INSTALL_PREFIX}/CMake"
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
if (NB_BUILD_TESTS)
|
if (NB_BUILD_TESTS)
|
||||||
add_subdirectory(./tests )
|
add_subdirectory(./tests)
|
||||||
endif()
|
endif()
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_DATASINK
|
||||||
|
#define _NB_DATASINK
|
||||||
|
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
#include "ThreadSafeQueue.hpp"
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
template<typename DataType>
|
||||||
|
class DataSink {
|
||||||
|
public:
|
||||||
|
DataSink(const DataSink&) = delete;
|
||||||
|
DataSink(DataSink&&) = delete;
|
||||||
|
DataSink& operator=(const DataSink&) = delete;
|
||||||
|
|
||||||
|
virtual bool isRunning() const noexcept {
|
||||||
|
return _running;
|
||||||
|
}
|
||||||
|
virtual bool stop() noexcept = 0;
|
||||||
|
virtual bool run() = 0;
|
||||||
|
virtual bool in(const DataType&) = 0;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
DataSink() = default;
|
||||||
|
|
||||||
|
std::atomic<bool> _running;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<typename DataType, typename BufferType, typename ProcessorType>
|
||||||
|
class BufferedDataProcessor : public DataSink<DataType> {
|
||||||
|
using Base = DataSink<DataType>;
|
||||||
|
public:
|
||||||
|
using Base::Base;
|
||||||
|
|
||||||
|
bool stop() noexcept { return type_ptr->stop(); }
|
||||||
|
bool run() { return type_ptr->run(); }
|
||||||
|
bool in(const DataType& val) { return type_ptr->in(val); }
|
||||||
|
|
||||||
|
protected:
|
||||||
|
unsigned int count() const {
|
||||||
|
return type_ptr->count();
|
||||||
|
}
|
||||||
|
void push(const DataType& val) {
|
||||||
|
type_ptr->push(val);
|
||||||
|
}
|
||||||
|
DataType pop() {
|
||||||
|
return type_ptr->pop();
|
||||||
|
}
|
||||||
|
void flush() {
|
||||||
|
type_ptr->flush();
|
||||||
|
}
|
||||||
|
void clear() {
|
||||||
|
type_ptr->clear();
|
||||||
|
}
|
||||||
|
bool process(const DataType& val) {
|
||||||
|
return type_ptr->process(val);
|
||||||
|
}
|
||||||
|
|
||||||
|
using Base::_running;
|
||||||
|
|
||||||
|
BufferType _buffer;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
template<typename DataType, typename ProcessorType>
|
||||||
|
class MultithreadedDataProcessor
|
||||||
|
: public BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType> {
|
||||||
|
using Base = BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType>;
|
||||||
|
public:
|
||||||
|
~MultithreadedDataProcessor() { type_ptr->stop(); }
|
||||||
|
|
||||||
|
bool isRunning() const noexcept override {
|
||||||
|
return this->_running && (_runningThread!=nullptr);
|
||||||
|
}
|
||||||
|
bool run() {
|
||||||
|
if (!type_ptr->isRunning()) {
|
||||||
|
this->_running = true;
|
||||||
|
_runningThread = std::make_shared<std::thread>([&]{
|
||||||
|
while(type_ptr->isRunning()) {
|
||||||
|
flush();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this->isRunning();
|
||||||
|
}
|
||||||
|
bool stop() noexcept override {
|
||||||
|
if (type_ptr->isRunning()) {
|
||||||
|
this->_running = false;
|
||||||
|
_runningThread->join();
|
||||||
|
_runningThread = nullptr;
|
||||||
|
}
|
||||||
|
return !type_ptr->isRunning();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
using Base::Base;
|
||||||
|
|
||||||
|
unsigned int count() const {
|
||||||
|
return this->_buffer.size();
|
||||||
|
}
|
||||||
|
void push(const DataType& val) {
|
||||||
|
this->_buffer.push(val);
|
||||||
|
};
|
||||||
|
DataType pop() {
|
||||||
|
std::shared_ptr<DataType> event;
|
||||||
|
this->_buffer.pop(event);
|
||||||
|
this->process(*event);
|
||||||
|
return *event;
|
||||||
|
}
|
||||||
|
void flush() {
|
||||||
|
while(type_ptr->count()) {
|
||||||
|
pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
void clear() {
|
||||||
|
this->_buffer.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shared_ptr<std::thread> _runningThread;
|
||||||
|
|
||||||
|
private:
|
||||||
|
ProcessorType* type_ptr = static_cast<ProcessorType*>(this);
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
} // namespace nb
|
||||||
|
#endif // _NB_DATASINK
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_ERROR
|
||||||
|
#define _NB_ERROR
|
||||||
|
|
||||||
|
#include <exception>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <type_traits>
|
||||||
|
#include "TypeTraits.hpp"
|
||||||
|
#include <unordered_map>
|
||||||
|
#include "Utils.hpp"
|
||||||
|
|
||||||
|
/* #ifndef THROW_WITH_INFO
|
||||||
|
#ifdef CODE_ERROR_LOCATIONS
|
||||||
|
#define THROW_WITH_INFO(type, ...) throw type(__VA_ARGS__, __LINE__, __FILE__)
|
||||||
|
#else
|
||||||
|
#define THROW_WITH_INFO(type, ...) throw type(__VA_ARGS__)
|
||||||
|
#endif // CODE_ERROR_LOCATIONS
|
||||||
|
#endif // THROW_WITH_INFO
|
||||||
|
|
||||||
|
#ifndef THROW
|
||||||
|
#ifdef LOGGING
|
||||||
|
#define THROW_WTIH_INFO(type, ...) throw type(__VA_ARGS__, __LINE__, __FILE__)
|
||||||
|
#else
|
||||||
|
#define THROW(...) THROW_WITH_INFO(__VA_ARGS__)
|
||||||
|
#endif // LOGGING
|
||||||
|
#endif // THROW */
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
typedef std::unordered_map<unsigned int, const char*> ErrorCodeMap;
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
using has_type = decltype(T::type);
|
||||||
|
|
||||||
|
template<class ErrorType = NoneType>
|
||||||
|
class ErrorBase;
|
||||||
|
|
||||||
|
template<>
|
||||||
|
class ErrorBase<NoneType> : public std::exception {
|
||||||
|
public:
|
||||||
|
const unsigned int code;
|
||||||
|
const std::string msg;
|
||||||
|
const std::shared_ptr<const std::exception> trace;
|
||||||
|
const bool traceIsNBError;
|
||||||
|
|
||||||
|
virtual inline std::string str() const noexcept = 0;
|
||||||
|
|
||||||
|
virtual const char* what() const noexcept override final {
|
||||||
|
const std::string& ret = str();
|
||||||
|
return ret.c_str();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
template <
|
||||||
|
typename TraceType = std::exception,
|
||||||
|
std::enable_if_t<std::is_base_of_v<std::exception, TraceType>, bool> = true
|
||||||
|
>
|
||||||
|
ErrorBase(
|
||||||
|
const unsigned int& code_,
|
||||||
|
const std::string& msg_,
|
||||||
|
const std::shared_ptr<TraceType> trace_,
|
||||||
|
const unsigned int& line_,
|
||||||
|
std::string filename_
|
||||||
|
) noexcept :
|
||||||
|
code(code_),
|
||||||
|
msg(msg_),
|
||||||
|
trace{std::dynamic_pointer_cast<std::exception>(trace_)},
|
||||||
|
traceIsNBError( trace_ ? is_detected<has_type, TraceType>::value : false)
|
||||||
|
{
|
||||||
|
static_assert(std::is_base_of<std::exception, TraceType>::value,
|
||||||
|
"`trace_` must be a pointer to a child object of std::exception."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
template <class ErrorType>
|
||||||
|
class ErrorBase : public ErrorBase<NoneType> {
|
||||||
|
using Base = ErrorBase<NoneType>;
|
||||||
|
public:
|
||||||
|
ErrorBase(const ErrorBase&) = default;
|
||||||
|
ErrorBase& operator=(const ErrorBase&) = delete;
|
||||||
|
|
||||||
|
virtual inline std::string str() const noexcept override {
|
||||||
|
std::string ret = msg;
|
||||||
|
if (trace) {
|
||||||
|
const std::string replace = nb::NEWLINE+" ";
|
||||||
|
std::string trace_msg;
|
||||||
|
if (traceIsNBError) {
|
||||||
|
trace_msg = std::static_pointer_cast<const ErrorBase>(trace)->str();
|
||||||
|
trace_msg = std::string(std::string_view(trace_msg).substr(
|
||||||
|
0, trace_msg.length()-nb::NEWLINE.length()
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
trace_msg = std::string(trace->what());
|
||||||
|
}
|
||||||
|
ret += replace + "Trace: " + find_and_replace<std::string>(
|
||||||
|
trace_msg,
|
||||||
|
nb::NEWLINE,
|
||||||
|
replace
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return ret + nb::NEWLINE;
|
||||||
|
}
|
||||||
|
|
||||||
|
static const std::string type;
|
||||||
|
static const ErrorCodeMap ErrorMessages;
|
||||||
|
|
||||||
|
using Base::code;
|
||||||
|
using Base::msg;
|
||||||
|
using Base::trace;
|
||||||
|
using Base::traceIsNBError;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
using Base::Base;
|
||||||
|
|
||||||
|
template <
|
||||||
|
typename TraceType = std::exception,
|
||||||
|
std::enable_if_t<std::is_base_of_v<std::exception, TraceType>, bool> = true
|
||||||
|
>
|
||||||
|
ErrorBase(
|
||||||
|
const unsigned int code_,
|
||||||
|
std::string msg_,
|
||||||
|
const TraceType* trace_=nullptr,
|
||||||
|
unsigned int line_=0,
|
||||||
|
std::string filename_=""
|
||||||
|
) : Base(
|
||||||
|
code_,
|
||||||
|
msg_,
|
||||||
|
trace_ ? std::make_shared<TraceType>(*trace_) : nullptr,
|
||||||
|
line_,
|
||||||
|
filename_
|
||||||
|
) {
|
||||||
|
static_assert(std::is_same<const std::unordered_map<unsigned int, const char*>, decltype(ErrorType::ErrorMessages)>::value,
|
||||||
|
"const std::unordered_map<unsigned int, const char*> ErrorMessages must be "
|
||||||
|
"a class member."
|
||||||
|
);
|
||||||
|
static_assert(std::is_enum_v<typename ErrorType::Codes>, "enum Codes must be a class member.");
|
||||||
|
static_assert(std::is_same<std::underlying_type_t<typename ErrorType::Codes>, unsigned int>::value,
|
||||||
|
"enum Codes must be of underlying type unsigned int."
|
||||||
|
);
|
||||||
|
static_assert(std::is_same<const std::string, decltype(ErrorType::type)>::value,
|
||||||
|
"const std::string type must be a class member."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <
|
||||||
|
typename TraceType,
|
||||||
|
std::enable_if_t<std::is_base_of_v<std::exception, TraceType>, bool> = true
|
||||||
|
>
|
||||||
|
ErrorBase(
|
||||||
|
const unsigned int& code_,
|
||||||
|
const TraceType& trace_,
|
||||||
|
unsigned int line_=0,
|
||||||
|
std::string filename_=""
|
||||||
|
) noexcept : ErrorBase(
|
||||||
|
code_,
|
||||||
|
ErrorType::ErrorMessages.at(code_),
|
||||||
|
&trace_,
|
||||||
|
line_,
|
||||||
|
filename_
|
||||||
|
) {}
|
||||||
|
|
||||||
|
template <
|
||||||
|
typename TraceType,
|
||||||
|
std::enable_if_t<std::is_base_of_v<std::exception, TraceType>, bool> = true
|
||||||
|
>
|
||||||
|
ErrorBase(
|
||||||
|
const std::string& msg_,
|
||||||
|
const TraceType& trace_,
|
||||||
|
unsigned int line_=0,
|
||||||
|
std::string filename_=""
|
||||||
|
) noexcept : ErrorBase(
|
||||||
|
0,
|
||||||
|
msg_,
|
||||||
|
&trace_,
|
||||||
|
line_,
|
||||||
|
filename_
|
||||||
|
) {}
|
||||||
|
|
||||||
|
ErrorBase(
|
||||||
|
const unsigned int& code_,
|
||||||
|
unsigned int line_=0,
|
||||||
|
std::string filename_=""
|
||||||
|
) noexcept : ErrorBase(
|
||||||
|
code_,
|
||||||
|
ErrorType::ErrorMessages.at(code_),
|
||||||
|
static_cast<std::exception*>(nullptr),
|
||||||
|
line_,
|
||||||
|
filename_
|
||||||
|
) {}
|
||||||
|
|
||||||
|
ErrorBase(
|
||||||
|
const std::string& msg_,
|
||||||
|
unsigned int line_=0,
|
||||||
|
std::string filename_=""
|
||||||
|
) noexcept : ErrorBase(
|
||||||
|
0,
|
||||||
|
msg_,
|
||||||
|
nullptr,
|
||||||
|
line_,
|
||||||
|
filename_
|
||||||
|
) {}
|
||||||
|
};
|
||||||
|
template <typename ErrorType>
|
||||||
|
const std::string ErrorBase<ErrorType>::type = ErrorType::type;
|
||||||
|
template <typename ErrorType>
|
||||||
|
const ErrorCodeMap ErrorBase<ErrorType>::ErrorMessages = ErrorType::ErrorMessages;
|
||||||
|
|
||||||
|
template <class ErrorType = NoneType>
|
||||||
|
class Error;
|
||||||
|
|
||||||
|
template<>
|
||||||
|
class Error<NoneType>;
|
||||||
|
|
||||||
|
template <class ErrorType>
|
||||||
|
class Error : public ErrorBase<ErrorType> {
|
||||||
|
using Base = ErrorBase<ErrorType>;
|
||||||
|
public:
|
||||||
|
template <typename... Args>
|
||||||
|
Error(Args... T) : Base(T...) {}
|
||||||
|
|
||||||
|
using Base::str;
|
||||||
|
using Base::what;
|
||||||
|
using Base::code;
|
||||||
|
using Base::msg;
|
||||||
|
using Base::trace;
|
||||||
|
using Base::type;
|
||||||
|
using Base::ErrorMessages;
|
||||||
|
|
||||||
|
friend ErrorBase<Error>;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<>
|
||||||
|
class Error<NoneType> : public ErrorBase<Error<NoneType>> {
|
||||||
|
using Base = ErrorBase<Error<NoneType>>;
|
||||||
|
public:
|
||||||
|
using Base::Base;
|
||||||
|
Error() : Base(0) {}
|
||||||
|
|
||||||
|
enum Codes : unsigned int {
|
||||||
|
GENERAL, UNDEFINED, BADERRORCODE
|
||||||
|
};
|
||||||
|
|
||||||
|
using Base::str;
|
||||||
|
using Base::what;
|
||||||
|
using Base::code;
|
||||||
|
using Base::msg;
|
||||||
|
using Base::trace;
|
||||||
|
|
||||||
|
static const std::string type;
|
||||||
|
static const ErrorCodeMap ErrorMessages;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace nb
|
||||||
|
|
||||||
|
#endif // _NB_ERROR
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_LOGGER
|
||||||
|
#define _NB_LOGGER
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <ostream>
|
||||||
|
#include <thread>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "DataSink.hpp"
|
||||||
|
#include "Processes.hpp"
|
||||||
|
#include "ThreadSafeQueue.hpp"
|
||||||
|
#include "TypeTraits.hpp"
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
typedef std::chrono::time_point<
|
||||||
|
std::chrono::system_clock,
|
||||||
|
std::chrono::nanoseconds
|
||||||
|
> LoggerTimePoint;
|
||||||
|
|
||||||
|
struct LogEvent{
|
||||||
|
const LoggerTimePoint time;
|
||||||
|
const unsigned char lvl;
|
||||||
|
const std::string msg;
|
||||||
|
const std::thread::id tid;
|
||||||
|
const uint64_t pid;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef std::string (*LogProcessFunction)(const LoggerTimePoint&, const std::string&);
|
||||||
|
typedef std::unordered_map<uint8_t, LogProcessFunction> LogProcessFunctionMap;
|
||||||
|
|
||||||
|
template<typename LogType, typename Logger, typename ST=std::ostream*>
|
||||||
|
class LoggerBase
|
||||||
|
: public MultithreadedDataProcessor<LogType, Logger>{
|
||||||
|
using StreamType = ST;
|
||||||
|
using LoggerType = Logger;
|
||||||
|
using Base = MultithreadedDataProcessor<LogType, LoggerType>;
|
||||||
|
public:
|
||||||
|
bool run() {
|
||||||
|
if (!type_ptr->isRunning()) {
|
||||||
|
this->_running = true;
|
||||||
|
this->_runningThread = std::make_shared<std::thread>([&]{
|
||||||
|
while(type_ptr->isRunning()) {
|
||||||
|
type_ptr->flush();
|
||||||
|
}
|
||||||
|
type_ptr->flush();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return type_ptr->isRunning();
|
||||||
|
}
|
||||||
|
protected:
|
||||||
|
LoggerBase() = default;
|
||||||
|
|
||||||
|
StreamType _ostream;
|
||||||
|
|
||||||
|
private:
|
||||||
|
LoggerType* type_ptr = static_cast<LoggerType*>(this);
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename LT>
|
||||||
|
class DebugLogger : public LoggerBase<LogEvent, LT, std::vector<std::ostream*>>{
|
||||||
|
using StreamType = std::vector<std::ostream*>;
|
||||||
|
using LoggerType = LT;
|
||||||
|
using Base = LoggerBase<LogEvent, LoggerType, StreamType>;
|
||||||
|
public:
|
||||||
|
|
||||||
|
template<typename... ST>
|
||||||
|
DebugLogger(ST&... streams) : _ostream(nb::RefPackToPtrVec<std::ostream, ST...>(streams...).vec) {}
|
||||||
|
|
||||||
|
~DebugLogger() { type_ptr->stop(); }
|
||||||
|
|
||||||
|
void log(const std::string& msg, const uint8_t& lvl=0xFF) {
|
||||||
|
type_ptr->push(LogEvent{
|
||||||
|
std::chrono::system_clock::now(),
|
||||||
|
lvl,
|
||||||
|
msg,
|
||||||
|
std::this_thread::get_id(),
|
||||||
|
GetPID(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
template <size_t N>
|
||||||
|
void log(char const(&msg) [N], const uint8_t& lvl=0xFF) {
|
||||||
|
type_ptr->log(std::string(msg), lvl);
|
||||||
|
}
|
||||||
|
|
||||||
|
void log(const std::exception& err, const uint8_t& lvl=0xFF) {
|
||||||
|
type_ptr->log(err.what(), lvl);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename U>
|
||||||
|
void warn(const U& val, const uint8_t& lvl=0x01) { type_ptr->log(val, lvl); }
|
||||||
|
|
||||||
|
template<typename U>
|
||||||
|
void error(const U& val) { type_ptr->log(val, 0xFF); }
|
||||||
|
|
||||||
|
protected:
|
||||||
|
std::vector<std::ostream*> _ostream;
|
||||||
|
|
||||||
|
private:
|
||||||
|
LoggerType* type_ptr = static_cast<LoggerType*>(this);
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
class DefaultDebugLogger : public DebugLogger<DefaultDebugLogger> {
|
||||||
|
using LoggerType = DefaultDebugLogger;
|
||||||
|
using Base = DebugLogger<DefaultDebugLogger>;
|
||||||
|
|
||||||
|
template <typename... Ts>
|
||||||
|
struct LogRow;
|
||||||
|
|
||||||
|
public:
|
||||||
|
using Base::Base;
|
||||||
|
|
||||||
|
~DefaultDebugLogger() { stop(); }
|
||||||
|
|
||||||
|
friend class BufferedDataProcessor<LogEvent, ThreadsafeQueue<LogEvent>, DefaultDebugLogger>;
|
||||||
|
|
||||||
|
template <typename STR, typename... Ts>
|
||||||
|
friend STR& operator<<(STR&, const DefaultDebugLogger::LogRow<Ts...>&);
|
||||||
|
|
||||||
|
protected:
|
||||||
|
using Base::_ostream;
|
||||||
|
|
||||||
|
bool process(const LogEvent& msg) {
|
||||||
|
for (const auto os : this->_ostream) {
|
||||||
|
*os << msg.lvl << "\t|\t" << msg.msg << "\n";
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
extern DefaultDebugLogger logger;
|
||||||
|
|
||||||
|
// Taking Charge of Adult ADHD by Russell Barkley
|
||||||
|
|
||||||
|
} // namespace nb
|
||||||
|
#endif // _NB_LOGGER
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
@PACKAGE_INIT@
|
|
||||||
include("${CMAKE_CURRENT_LIST_DIR}/NBCoreTargets.cmake")
|
|
||||||
@@ -7,11 +7,6 @@
|
|||||||
namespace nb {
|
namespace nb {
|
||||||
|
|
||||||
uint64_t GetPID();
|
uint64_t GetPID();
|
||||||
uint64_t GetTID();
|
|
||||||
|
|
||||||
extern thread_local const uint64_t CurrentTID;
|
|
||||||
static const uint64_t MainTID = GetTID();
|
|
||||||
|
|
||||||
|
|
||||||
} // namespace nb
|
} // namespace nb
|
||||||
|
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_TYPE_TRAITS
|
||||||
|
#define _NB_TYPE_TRAITS
|
||||||
|
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
namespace detail {
|
||||||
|
template <
|
||||||
|
class Default,
|
||||||
|
class AlwaysVoid,
|
||||||
|
template <class...> class Op,
|
||||||
|
class... Args
|
||||||
|
>
|
||||||
|
struct detector {
|
||||||
|
using value = std::false_type;
|
||||||
|
using type = Default;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <
|
||||||
|
class Default,
|
||||||
|
template <class...> class Op,
|
||||||
|
class... Args
|
||||||
|
>
|
||||||
|
struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> {
|
||||||
|
using value = std::true_type;
|
||||||
|
using type = Op<Args...>;
|
||||||
|
};
|
||||||
|
} // namespace detail
|
||||||
|
|
||||||
|
struct NoneType{};
|
||||||
|
|
||||||
|
template <
|
||||||
|
template <class...> class Op,
|
||||||
|
class... Args
|
||||||
|
>
|
||||||
|
using is_detected = typename detail::detector<NoneType, void, Op, Args...>::value;
|
||||||
|
|
||||||
|
/*template<std::size_t N=0, typename Func, typename... Pack>
|
||||||
|
inline typename std::enable_if<N==sizeof...(Pack), void>::type
|
||||||
|
ForEach(std::tuple<Pack...>&, Func) {}
|
||||||
|
|
||||||
|
template<std::size_t N=0, typename Func, typename... Pack>
|
||||||
|
inline typename std::enable_if<N < sizeof...(Pack), void>::type
|
||||||
|
ForEach(std::tuple<Pack...>& tup, Func f) {
|
||||||
|
f(N, std::get<N>(tup));
|
||||||
|
ForEach<N+1, Func, Pack...>(tup, f);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<std::size_t N=0, typename Func, typename Args, typename... Pack>
|
||||||
|
inline typename std::enable_if<N==sizeof...(Pack), void>::type
|
||||||
|
ForEach(std::tuple<Pack...>&, Func, const Args&) {}
|
||||||
|
|
||||||
|
template<std::size_t N=0, typename Func, typename Args, typename... Pack>
|
||||||
|
inline typename std::enable_if<N < sizeof...(Pack), void>::type
|
||||||
|
ForEach(std::tuple<Pack...>& tup, Func f, const Args& arg) {
|
||||||
|
f(N, std::get<N>(tup), arg);
|
||||||
|
ForEach<N+1, Func, Args, Pack...>(tup, f, arg);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename Pack1, typename... Pack>
|
||||||
|
struct RefPackToPtrVec {
|
||||||
|
RefPackToPtrVec(std::vector<T*> _vec, Pack1& p1, Pack&... packs)
|
||||||
|
: vec(_vec) {
|
||||||
|
static_assert(std::is_base_of<T, Pack1>::value);
|
||||||
|
vec.push_back(&p1);
|
||||||
|
vec = RefPackToPtrVec<T, Pack...>(vec, packs...).vec;
|
||||||
|
}
|
||||||
|
|
||||||
|
RefPackToPtrVec(Pack1& p1, Pack&... packs)
|
||||||
|
: RefPackToPtrVec({}, p1, packs...) {}
|
||||||
|
|
||||||
|
std::vector<T*> vec;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T, typename Pack>
|
||||||
|
struct RefPackToPtrVec<T, Pack> {
|
||||||
|
RefPackToPtrVec(std::vector<T*> _vec, Pack& p1)
|
||||||
|
: vec(_vec) {
|
||||||
|
static_assert(std::is_base_of<T, Pack>::value);
|
||||||
|
vec.push_back(&p1);
|
||||||
|
}
|
||||||
|
|
||||||
|
RefPackToPtrVec(Pack& p1)
|
||||||
|
: RefPackToPtrVec({}, p1) {}
|
||||||
|
|
||||||
|
std::vector<T*> vec;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T, typename... Pack>
|
||||||
|
struct PackIsSameType;
|
||||||
|
|
||||||
|
template <typename T, typename PackType>
|
||||||
|
struct PackIsSameType<T, PackType> {
|
||||||
|
const bool value = std::is_base_of<T, PackType>::value;
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename T, typename FirstPack, typename... Pack>
|
||||||
|
struct PackIsSameType<T, FirstPack, Pack...> {
|
||||||
|
const bool value = std::is_base_of<T, FirstPack>::value && PackIsSameType<T, Pack...>::value;
|
||||||
|
};*/
|
||||||
|
|
||||||
|
} // namespace nb
|
||||||
|
|
||||||
|
#endif // _NB_TYPE_TRAITS
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_CORE_TYPES
|
||||||
|
#define _NB_CORE_TYPES
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
#ifdef _NB_TARGET_WINDOWS
|
||||||
|
const std::string NEWLINE = "\n";
|
||||||
|
const std::wstring WNEWLINE = L"\n";
|
||||||
|
#endif // _NB_TARGET_WINDOWS
|
||||||
|
#ifdef _NB_TARGET_LINUX
|
||||||
|
const std::string NEWLINE = "\n";
|
||||||
|
const std::wstring WNEWLINE = L"\n";
|
||||||
|
#endif // _NB_TARGET_LINUX
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
std::enable_if_t<std::is_convertible_v<T, std::string>, std::wstring> str_to_wstr(T in) {
|
||||||
|
std::string str(in);
|
||||||
|
std::wstring ret(str.begin(), str.end());
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
std::enable_if_t<std::is_convertible_v<T, std::wstring>, std::string> wstr_to_str(T in) {
|
||||||
|
std::wstring wstr(in);
|
||||||
|
std::size_t wstrlen = wstr.length();
|
||||||
|
char* c_str= new char[wstrlen];
|
||||||
|
std::wcstombs(c_str, wstr.c_str(), wstrlen);
|
||||||
|
std::string ret(c_str, wstrlen);
|
||||||
|
delete[] c_str;
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Stream, typename... Args>
|
||||||
|
void stream(Stream& s, Args&&... args);
|
||||||
|
|
||||||
|
template <typename Stream, typename... Args>
|
||||||
|
void stream(Stream& s, Args&&... args) {
|
||||||
|
(s << ... << args);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename... Args>
|
||||||
|
void term(Args&&... args) { stream(std::cout, args..., nb::NEWLINE); }
|
||||||
|
|
||||||
|
template<typename... Args>
|
||||||
|
void wterm(Args&&... args) { stream(std::wcout, args..., nb::WNEWLINE); }
|
||||||
|
|
||||||
|
template <typename T = std::string, typename A, typename B, typename C>
|
||||||
|
T find_and_replace(
|
||||||
|
A original,
|
||||||
|
B find,
|
||||||
|
C replace
|
||||||
|
) {
|
||||||
|
const T& original_t = T(original);
|
||||||
|
const T& find_t = T(find);
|
||||||
|
const T& replace_t = T(replace);
|
||||||
|
|
||||||
|
T ret = original_t;
|
||||||
|
|
||||||
|
std::size_t find_len = find_t.length();
|
||||||
|
std::size_t replace_len = replace_t.length();
|
||||||
|
std::size_t currpos = 0;
|
||||||
|
while(true) {
|
||||||
|
currpos = ret.find(find_t, currpos);
|
||||||
|
if (currpos == T::npos) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ret = ret.erase(currpos, find_len);
|
||||||
|
ret = ret.insert(currpos, replace_t);
|
||||||
|
currpos += replace_len;
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* template<typename T>
|
||||||
|
T swap_endian(const T& val) {
|
||||||
|
T ret;
|
||||||
|
const int size = sizeof(T);
|
||||||
|
auto retLoc = static_cast<void*>(&ret);
|
||||||
|
auto valLoc = static_cast<const void*>(&val);
|
||||||
|
|
||||||
|
for (int i = 0; i < size; ++i) {
|
||||||
|
memcpy(retLoc+i, valLoc+(size-i-1), 1);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
} */
|
||||||
|
|
||||||
|
|
||||||
|
// using ByteVector = std::vector<uint8_t>;
|
||||||
|
|
||||||
|
} // namespace nb
|
||||||
|
#endif // _NB_CORE_TYPES
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_DATASINK
|
|
||||||
#define _NB_DATASINK
|
|
||||||
|
|
||||||
#include <atomic>
|
|
||||||
#include <thread>
|
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
#include <NBCore/ThreadSafeQueue.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
template<typename DataType>
|
|
||||||
class DataSink {
|
|
||||||
public:
|
|
||||||
DataSink(const DataSink&) = delete;
|
|
||||||
DataSink(DataSink&&) = delete;
|
|
||||||
DataSink& operator=(const DataSink&) = delete;
|
|
||||||
|
|
||||||
virtual bool isRunning() const noexcept {
|
|
||||||
std::atomic_thread_fence(std::memory_order_acquire);
|
|
||||||
return _running.load(std::memory_order_acquire);
|
|
||||||
}
|
|
||||||
virtual bool stop() noexcept = 0;
|
|
||||||
virtual bool run() = 0;
|
|
||||||
virtual bool in(const DataType&) = 0;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
DataSink() {
|
|
||||||
_running.store(false, std::memory_order_release);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::atomic<bool> _running;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename DataType, typename SinkTypes=DataSink<DataType>>
|
|
||||||
class MultiSink : public DataSink<DataType> {
|
|
||||||
protected:
|
|
||||||
using Base = DataSink<DataType>;
|
|
||||||
using SinkPtr = std::shared_ptr<SinkTypes>;
|
|
||||||
using Base::_running;
|
|
||||||
std::vector<SinkPtr> _sinks;
|
|
||||||
|
|
||||||
public:
|
|
||||||
MultiSink(std::vector<SinkPtr> sinks={}) : _sinks(sinks) {}
|
|
||||||
virtual void addSink(SinkPtr sink) {
|
|
||||||
_sinks.push_back(sink);
|
|
||||||
}
|
|
||||||
virtual std::vector<SinkPtr>& getSinks() { return _sinks; }
|
|
||||||
bool isRunning() const noexcept override {
|
|
||||||
return Base::isRunning();
|
|
||||||
}
|
|
||||||
bool stop() noexcept override {
|
|
||||||
_running.store(false, std::memory_order_release);
|
|
||||||
for (auto& sink : _sinks) {
|
|
||||||
sink->stop();
|
|
||||||
}
|
|
||||||
return isRunning();
|
|
||||||
}
|
|
||||||
bool run() override {
|
|
||||||
_running.store(true, std::memory_order_release);
|
|
||||||
for (auto& sink : _sinks) {
|
|
||||||
sink->run();
|
|
||||||
}
|
|
||||||
return isRunning();
|
|
||||||
}
|
|
||||||
bool in(const DataType& data) override {
|
|
||||||
if (isRunning()) {
|
|
||||||
bool success = true;
|
|
||||||
for (auto& sink : _sinks) {
|
|
||||||
success &= sink->in(data);
|
|
||||||
}
|
|
||||||
return success;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename DataType, typename BufferType, typename ProcessorType>
|
|
||||||
class BufferedDataProcessor : public DataSink<DataType> {
|
|
||||||
private:
|
|
||||||
ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Base = DataSink<DataType>;
|
|
||||||
using Base::_running;
|
|
||||||
BufferType _buffer;
|
|
||||||
virtual unsigned int count() const {
|
|
||||||
return type_ptr->count();
|
|
||||||
}
|
|
||||||
virtual bool pop(std::shared_ptr<DataType> ret) {
|
|
||||||
return type_ptr->pop(ret);
|
|
||||||
}
|
|
||||||
virtual void flush() {
|
|
||||||
type_ptr->flush();
|
|
||||||
}
|
|
||||||
virtual void clear() {
|
|
||||||
type_ptr->clear();
|
|
||||||
}
|
|
||||||
virtual bool process(const DataType& val) = 0;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
virtual bool stop() noexcept override { return type_ptr->stop(); }
|
|
||||||
virtual bool run() override { return type_ptr->run(); }
|
|
||||||
virtual bool in(const DataType& val) override { return type_ptr->in(val); }
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename DataType, typename ProcessorType>
|
|
||||||
class MultithreadedDataProcessor
|
|
||||||
: public BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType> {
|
|
||||||
private:
|
|
||||||
ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
|
|
||||||
std::mutex _pause;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Base = BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType>;
|
|
||||||
using Base::Base;
|
|
||||||
using Base::process;
|
|
||||||
using Base::_running;
|
|
||||||
std::shared_ptr<std::thread> _runningThread;
|
|
||||||
virtual unsigned int count() const override {
|
|
||||||
return type_ptr->_buffer.size();
|
|
||||||
}
|
|
||||||
virtual bool pop(std::shared_ptr<DataType> ret=nullptr) override {
|
|
||||||
type_ptr->_buffer.pop(ret);
|
|
||||||
return this->process(*ret);
|
|
||||||
}
|
|
||||||
virtual bool popBlock(std::shared_ptr<DataType> ret=nullptr) {
|
|
||||||
ret = type_ptr->_buffer.popBlock();
|
|
||||||
return this->process(*ret);
|
|
||||||
}
|
|
||||||
virtual void flush() override {
|
|
||||||
while(type_ptr->count()) {
|
|
||||||
type_ptr->pop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
virtual void clear() override {
|
|
||||||
type_ptr->_buffer.empty();
|
|
||||||
}
|
|
||||||
virtual std::unique_lock<std::mutex> pause() {
|
|
||||||
return std::move(std::unique_lock<std::mutex>(_pause));
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::isRunning;
|
|
||||||
virtual ~MultithreadedDataProcessor() { type_ptr->stop(); }
|
|
||||||
|
|
||||||
bool run() override {
|
|
||||||
if (!type_ptr->isRunning()) {
|
|
||||||
_running.store(true, std::memory_order_release);
|
|
||||||
_runningThread = std::make_shared<std::thread>([&]{
|
|
||||||
while(type_ptr->isRunning()) {
|
|
||||||
std::lock_guard<std::mutex> lock(_pause);
|
|
||||||
type_ptr->flush();
|
|
||||||
}
|
|
||||||
type_ptr->flush();
|
|
||||||
type_ptr->stop();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return type_ptr->isRunning();
|
|
||||||
}
|
|
||||||
bool stop() noexcept override {
|
|
||||||
if (type_ptr->isRunning()) {
|
|
||||||
_running.store(false, std::memory_order_release);
|
|
||||||
if (_runningThread) {
|
|
||||||
_runningThread->join();
|
|
||||||
_runningThread = nullptr;
|
|
||||||
}
|
|
||||||
type_ptr->flush();
|
|
||||||
}
|
|
||||||
return !type_ptr->isRunning();
|
|
||||||
}
|
|
||||||
bool in(const DataType& val) override {
|
|
||||||
type_ptr->_buffer.push(val);
|
|
||||||
return type_ptr->isRunning();
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#endif // _NB_DATASINK
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_ERROR
|
|
||||||
#define _NB_ERROR
|
|
||||||
|
|
||||||
#include <NBCore/ErrorsImpl.hpp>
|
|
||||||
#include <NBCore/Logger.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
#ifdef _NB_AUTOLOG
|
|
||||||
#ifndef LOG_W_CODE_LOC
|
|
||||||
#define LOG_W_CODE_LOC(file, line, args...) nb::logger.msg(args, file, line)
|
|
||||||
#endif // LOG_W_CODE_LOC
|
|
||||||
#ifndef WARN_W_CODE_LOC
|
|
||||||
#define WARN_W_CODE_LOC(file, line, args...) nb::logger.warn(args, file, line)
|
|
||||||
#endif // WARN_W_CODE_LOC
|
|
||||||
#ifndef ERROR_W_CODE_LOC
|
|
||||||
#define ERROR_W_CODE_LOC(file, line, args...) nb::logger.error(args, file, line)
|
|
||||||
#endif // ERROR_W_CODE_LOC
|
|
||||||
#ifdef _NB_CODE_ERROR_LOCATIONS
|
|
||||||
#ifndef LOG
|
|
||||||
#define LOG(arg) LOG_W_CODE_LOC(__FILE__, __LINE__, arg)
|
|
||||||
#endif // LOG
|
|
||||||
#ifndef WARN
|
|
||||||
#define WARN(args...) WARN_W_CODE_LOC(__FILE__, __LINE__, args)
|
|
||||||
#endif // WARN
|
|
||||||
#ifndef ERROR
|
|
||||||
#define ERROR(arg) ERROR_W_CODE_LOC(__FILE__, __LINE__, arg)
|
|
||||||
#endif // ERROR
|
|
||||||
#else
|
|
||||||
#ifndef LOG
|
|
||||||
#define LOG(args) nb::logger.msg(args)
|
|
||||||
#endif // LOG
|
|
||||||
#ifndef WARN
|
|
||||||
#define WARN(args...) nb::logger.warn(args)
|
|
||||||
#endif // WARN
|
|
||||||
#ifndef ERROR
|
|
||||||
#define ERROR(args) nb::logger.error(args)
|
|
||||||
#endif // ERROR
|
|
||||||
#endif // _NB_CODE_ERROR_LOCATIONS
|
|
||||||
#ifndef THROW_W_CODE_LOC
|
|
||||||
#define THROW_W_CODE_LOC(file, line, args...) ERROR_W_CODE_LOC(file, line, args); throw args
|
|
||||||
#endif // THROW_W_CODE_LOC
|
|
||||||
#else
|
|
||||||
#ifndef LOG
|
|
||||||
#define LOG(args)
|
|
||||||
#endif // LOG
|
|
||||||
#ifndef WARN
|
|
||||||
#define WARN(args...)
|
|
||||||
#endif // WARN
|
|
||||||
#ifndef ERROR
|
|
||||||
#define ERROR(args)
|
|
||||||
#endif // ERROR
|
|
||||||
#endif // _NB_AUTOLOG
|
|
||||||
|
|
||||||
#ifndef THROW
|
|
||||||
#ifdef _NB_AUTOLOG
|
|
||||||
#define THROW(args...) THROW_W_CODE_LOC(__FILE__, __LINE__, args)
|
|
||||||
#else
|
|
||||||
#define THROW(args...) throw args
|
|
||||||
#endif // _NB_AUTOLOG
|
|
||||||
#endif // THROW
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
#endif // _NB_ERROR
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_ERRORS_IMPL
|
|
||||||
#define _NB_ERRORS_IMPL
|
|
||||||
|
|
||||||
#include <exception>
|
|
||||||
#include <memory>
|
|
||||||
#include <string>
|
|
||||||
#include <type_traits>
|
|
||||||
|
|
||||||
#include <NBCore/StringUtils.hpp>
|
|
||||||
#include <NBCore/Utils.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
using ErrorCodeMap = ConstantMap<unsigned int, std::string>;
|
|
||||||
|
|
||||||
class ErrorBase {
|
|
||||||
protected:
|
|
||||||
|
|
||||||
public:
|
|
||||||
const unsigned int code;
|
|
||||||
const std::string msg;
|
|
||||||
const std::string type;
|
|
||||||
const std::shared_ptr<ErrorBase> trace;
|
|
||||||
|
|
||||||
ErrorBase(const ErrorBase&) = default;
|
|
||||||
ErrorBase(const std::exception&) noexcept;
|
|
||||||
virtual std::string what() const noexcept {
|
|
||||||
std::string ret = msg;
|
|
||||||
if (trace) {
|
|
||||||
std::string trace_msg = trace->what();
|
|
||||||
ret += NEWLINE + indent_strblock(
|
|
||||||
trace_msg,
|
|
||||||
TABOVER,
|
|
||||||
TABOVER+"Trace: "
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
ErrorBase(
|
|
||||||
unsigned int code_,
|
|
||||||
std::string msg_,
|
|
||||||
std::string type_,
|
|
||||||
std::shared_ptr<ErrorBase> trace_
|
|
||||||
) noexcept :
|
|
||||||
code(code_),
|
|
||||||
msg(msg_),
|
|
||||||
type(type_),
|
|
||||||
trace{trace_}
|
|
||||||
{}
|
|
||||||
};
|
|
||||||
|
|
||||||
template <class ErrorType=NoneType>
|
|
||||||
class Error : public ErrorBase {
|
|
||||||
private:
|
|
||||||
void inline check_asserts() {
|
|
||||||
static_assert(std::is_same<const ErrorCodeMap, decltype(ErrorType::ErrorMessages)>::value,
|
|
||||||
"const std::unordered_map<unsigned int, const char*> ErrorMessages must be "
|
|
||||||
"a class member."
|
|
||||||
);
|
|
||||||
static_assert(std::is_enum_v<typename ErrorType::Codes>, "enum Codes must be a class member.");
|
|
||||||
static_assert(std::is_same<std::underlying_type_t<typename ErrorType::Codes>, unsigned int>::value,
|
|
||||||
"enum Codes must be of underlying type unsigned int."
|
|
||||||
);
|
|
||||||
static_assert(std::is_same<const std::string, decltype(ErrorType::type)>::value,
|
|
||||||
"const std::string type must be a class member."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using ErrorBase::ErrorBase;
|
|
||||||
|
|
||||||
Error(
|
|
||||||
unsigned int code_,
|
|
||||||
const ErrorBase& trace_
|
|
||||||
) noexcept : ErrorBase(
|
|
||||||
code_,
|
|
||||||
ErrorType::ErrorMessages[code_],
|
|
||||||
ErrorType::type,
|
|
||||||
std::make_shared<ErrorBase>(trace_)
|
|
||||||
) { check_asserts(); }
|
|
||||||
|
|
||||||
Error(
|
|
||||||
std::string msg_,
|
|
||||||
const ErrorBase& trace_
|
|
||||||
) noexcept : ErrorBase(
|
|
||||||
ErrorType::Codes::UNDEFINED,
|
|
||||||
msg_,
|
|
||||||
ErrorType::type,
|
|
||||||
std::make_shared<ErrorBase>(trace_)
|
|
||||||
) { check_asserts(); }
|
|
||||||
|
|
||||||
Error(unsigned int code_) noexcept : ErrorBase(
|
|
||||||
code_,
|
|
||||||
ErrorType::ErrorMessages[code_],
|
|
||||||
ErrorType::type,
|
|
||||||
nullptr
|
|
||||||
) { check_asserts(); }
|
|
||||||
|
|
||||||
Error(std::string msg_) noexcept : ErrorBase(
|
|
||||||
ErrorType::Codes::UNDEFINED,
|
|
||||||
msg_,
|
|
||||||
ErrorType::type,
|
|
||||||
nullptr
|
|
||||||
) { check_asserts(); }
|
|
||||||
|
|
||||||
Error(
|
|
||||||
unsigned int code_,
|
|
||||||
const std::string& note_,
|
|
||||||
const ErrorBase& trace_
|
|
||||||
) noexcept : ErrorBase(
|
|
||||||
code_,
|
|
||||||
ErrorType::ErrorMessages[code_] + " (" + note_ + ")",
|
|
||||||
ErrorType::type,
|
|
||||||
std::make_shared<ErrorBase>(trace_)
|
|
||||||
) { check_asserts(); }
|
|
||||||
|
|
||||||
Error(unsigned int code_, const std::string& note_) noexcept : ErrorBase(
|
|
||||||
code_,
|
|
||||||
ErrorType::ErrorMessages[code_] + " (" + note_ + ")",
|
|
||||||
ErrorType::type,
|
|
||||||
nullptr
|
|
||||||
) { check_asserts(); }
|
|
||||||
|
|
||||||
using ErrorBase::what;
|
|
||||||
using ErrorBase::code;
|
|
||||||
using ErrorBase::msg;
|
|
||||||
using ErrorBase::trace;
|
|
||||||
using ErrorBase::type;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
class Error<NoneType> : public Error<Error<NoneType>> {
|
|
||||||
protected:
|
|
||||||
using Base = Error<Error<NoneType>>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::what;
|
|
||||||
using Base::code;
|
|
||||||
using Base::trace;
|
|
||||||
using Base::Base;
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
STANDARD, UNDEFINED, OUT_OF_RANGE, VALUE_ERROR, OVERWRITE_ERROR
|
|
||||||
};
|
|
||||||
inline static const std::string type = "nb::Error";
|
|
||||||
inline static const ErrorCodeMap ErrorMessages = {
|
|
||||||
{STANDARD, "std::exception"},
|
|
||||||
{UNDEFINED, "Error"},
|
|
||||||
{OUT_OF_RANGE, "Out-of-range error"},
|
|
||||||
{VALUE_ERROR, "Invalid value"},
|
|
||||||
{OVERWRITE_ERROR, "Attempting to overwrite managed data"}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
Error(unsigned int code_=1) noexcept : Base(code_) {}
|
|
||||||
Error(const std::exception& err) : Base(
|
|
||||||
STANDARD,
|
|
||||||
std::string(err.what()),
|
|
||||||
"std::exception",
|
|
||||||
nullptr
|
|
||||||
) {}
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename... Args>
|
|
||||||
Error(Args...) -> Error<NoneType>;
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
#endif // _NB_ERRORS_IMPL
|
|
||||||
@@ -1,250 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_LOGGER
|
|
||||||
#define _NB_LOGGER
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <thread>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include <NBCore/DataSink.hpp>
|
|
||||||
#include <NBCore/ErrorsImpl.hpp>
|
|
||||||
#include <NBCore/Printer.hpp>
|
|
||||||
#include <NBCore/Processes.hpp>
|
|
||||||
#include <NBCore/ThreadSafeQueue.hpp>
|
|
||||||
#include <NBCore/TypeTraits.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
class ErrorBase;
|
|
||||||
|
|
||||||
typedef std::chrono::time_point<
|
|
||||||
std::chrono::system_clock,
|
|
||||||
std::chrono::nanoseconds
|
|
||||||
> LoggerTimePoint;
|
|
||||||
|
|
||||||
typedef std::string (*LogProcessFunction)(const LoggerTimePoint&, const std::string&);
|
|
||||||
typedef std::unordered_map<uint8_t, LogProcessFunction> LogProcessFunctionMap;
|
|
||||||
|
|
||||||
template<typename LogType, typename Logger>
|
|
||||||
class LoggerBase : public MultithreadedDataProcessor<LogType, Logger>{
|
|
||||||
private:
|
|
||||||
Logger* const type_ptr = static_cast<LoggerType*>(this);
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using LoggerType = Logger;
|
|
||||||
using Base = MultithreadedDataProcessor<LogType, LoggerType>;
|
|
||||||
using SinkType = DataSink<LogType>;
|
|
||||||
using Base::process;
|
|
||||||
std::shared_ptr<SinkType> _logsink;
|
|
||||||
LoggerBase(std::shared_ptr<SinkType> sink) : _logsink(sink) {}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::flush;
|
|
||||||
bool run() override {
|
|
||||||
_logsink->run();
|
|
||||||
return Base::run();
|
|
||||||
}
|
|
||||||
using Base::pause;
|
|
||||||
bool stop() noexcept override {
|
|
||||||
auto ret = Base::stop();
|
|
||||||
_logsink->stop();
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
struct LogEvent{
|
|
||||||
const LoggerTimePoint time;
|
|
||||||
const unsigned char lvl;
|
|
||||||
const std::string msg;
|
|
||||||
const std::thread::id tid;
|
|
||||||
const uint64_t pid;
|
|
||||||
const std::string file="";
|
|
||||||
const unsigned int line=0;
|
|
||||||
};
|
|
||||||
|
|
||||||
class LogEventHandler : public DataSink<LogEvent> {
|
|
||||||
protected:
|
|
||||||
using Base = DataSink<LogEvent>;
|
|
||||||
using Base::_running;
|
|
||||||
std::atomic<uint8_t> _logLevel;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::isRunning;
|
|
||||||
LogEventHandler(uint8_t logging_level=0x01);
|
|
||||||
virtual uint8_t logLevel(uint8_t);
|
|
||||||
virtual uint8_t logLevel() const;
|
|
||||||
bool stop() noexcept override;
|
|
||||||
bool run() override;
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename LT>
|
|
||||||
class DebugLogger : public LoggerBase<LogEvent, LT>{
|
|
||||||
private:
|
|
||||||
LT* const type_ptr = static_cast<LT*>(this);
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using LoggerType = LT;
|
|
||||||
using Base = LoggerBase<LogEvent, LoggerType>;
|
|
||||||
using SinkType = LogEventHandler;
|
|
||||||
using SinkPtr = std::shared_ptr<SinkType>;
|
|
||||||
using Distributor = MultiSink<LogEvent, LogEventHandler>;
|
|
||||||
using Base::_logsink;
|
|
||||||
using Base::process;
|
|
||||||
std::atomic<uint8_t> _loglvl;
|
|
||||||
virtual void write_message(
|
|
||||||
std::string msg,
|
|
||||||
uint8_t lvl=0x00,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) {
|
|
||||||
type_ptr->in(LogEvent{
|
|
||||||
std::chrono::system_clock::now(),
|
|
||||||
lvl,
|
|
||||||
msg,
|
|
||||||
std::this_thread::get_id(),
|
|
||||||
GetPID(),
|
|
||||||
file,
|
|
||||||
line
|
|
||||||
});
|
|
||||||
}
|
|
||||||
template <size_t N>
|
|
||||||
void write_message(
|
|
||||||
char const(&msg) [N],
|
|
||||||
uint8_t lvl=0x00,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) {
|
|
||||||
this->write_message(std::string(msg), lvl, file, line);
|
|
||||||
}
|
|
||||||
void write_message(
|
|
||||||
const ErrorBase& err,
|
|
||||||
uint8_t lvl=0x00,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) {
|
|
||||||
this->write_message(err.what(), lvl, file, line);
|
|
||||||
}
|
|
||||||
template<typename U>
|
|
||||||
std::enable_if_t<std::is_integral_v<U>, void> write_message(
|
|
||||||
const U& val,
|
|
||||||
uint8_t lvl=0x00,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) {
|
|
||||||
this->write_message(std::to_string(val), lvl, file, line);
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
DebugLogger(std::vector<SinkPtr> sinks={}) : Base(
|
|
||||||
std::static_pointer_cast<DataSink<LogEvent>>(std::make_shared<Distributor>())
|
|
||||||
) {
|
|
||||||
for (auto sink : sinks) {
|
|
||||||
addLogHandler(sink);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
~DebugLogger() { static_cast<LoggerType*>(this)->stop(); }
|
|
||||||
void addLogHandler(SinkPtr sink) {
|
|
||||||
auto multsink = std::static_pointer_cast<Distributor>(_logsink);
|
|
||||||
multsink->addSink(sink);
|
|
||||||
}
|
|
||||||
uint8_t minimalLogLevel() const {
|
|
||||||
return _loglvl.load(std::memory_order_acquire);
|
|
||||||
}
|
|
||||||
uint8_t minimalLogLevel(uint8_t level) {
|
|
||||||
_loglvl.store(level, std::memory_order_release);
|
|
||||||
auto multsink = std::static_pointer_cast<Distributor>(_logsink);
|
|
||||||
for (auto& sink : multsink->getSinks()) {
|
|
||||||
if (sink->logLevel() < level) {
|
|
||||||
sink->logLevel(level);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return minimalLogLevel();
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename U>
|
|
||||||
void msg(
|
|
||||||
U val,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) { this->write_message(val, 0x00, file, line); }
|
|
||||||
|
|
||||||
template<typename U>
|
|
||||||
void warn(
|
|
||||||
U val,
|
|
||||||
uint8_t lvl=0x01,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) { this->write_message(val, lvl, file, line); }
|
|
||||||
|
|
||||||
void error(
|
|
||||||
const ErrorBase& val,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) {
|
|
||||||
this->write_message(val, 0xFF, file, line);
|
|
||||||
auto lock = this->pause();
|
|
||||||
this->flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
void error(
|
|
||||||
const std::string& val,
|
|
||||||
std::string file="",
|
|
||||||
unsigned int line=0
|
|
||||||
) {
|
|
||||||
this->write_message(Error<>(val), 0xFF, file, line);
|
|
||||||
auto lock = this->pause();
|
|
||||||
this->flush();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
class DefaultTerminalLogEventPrinter : public LogEventHandler {
|
|
||||||
protected:
|
|
||||||
using Base = LogEventHandler;
|
|
||||||
using Base::_running;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::isRunning;
|
|
||||||
using Base::logLevel;
|
|
||||||
using Base::stop;
|
|
||||||
using Base::run;
|
|
||||||
using Base::Base;
|
|
||||||
bool in(const LogEvent&) override;
|
|
||||||
};
|
|
||||||
|
|
||||||
class DefaultDebugLogger : public DebugLogger<DefaultDebugLogger> {
|
|
||||||
protected:
|
|
||||||
using LoggerType = DefaultDebugLogger;
|
|
||||||
using Base = DebugLogger<DefaultDebugLogger>;
|
|
||||||
using MultiLogSink = MultiSink<LogEvent>;
|
|
||||||
using SinkPtr = std::shared_ptr<LogEventHandler>;
|
|
||||||
using Base::_logsink;
|
|
||||||
using Base::write_message;
|
|
||||||
virtual bool process(const LogEvent& msg) override;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
using Base::msg;
|
|
||||||
using Base::warn;
|
|
||||||
using Base::error;
|
|
||||||
using Base::addLogHandler;
|
|
||||||
using Base::minimalLogLevel;
|
|
||||||
DefaultDebugLogger(std::vector<SinkPtr> sinks={}) : Base(sinks) {}
|
|
||||||
~DefaultDebugLogger() { stop(); }
|
|
||||||
|
|
||||||
friend class BufferedDataProcessor<LogEvent, ThreadsafeQueue<LogEvent>, DefaultDebugLogger>;
|
|
||||||
};
|
|
||||||
|
|
||||||
extern const bool LOGGER_RUNNING;
|
|
||||||
|
|
||||||
extern const bool LOGGER_RUNNING;
|
|
||||||
#ifdef _NB_AUTOLOG
|
|
||||||
extern DefaultDebugLogger logger;
|
|
||||||
#endif // _NB_AUTOLOG
|
|
||||||
|
|
||||||
// Taking Charge of Adult ADHD by Russell Barkley
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
#endif // _NB_LOGGER
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_PRINTER
|
|
||||||
#define _NB_PRINTER
|
|
||||||
|
|
||||||
#include <condition_variable>
|
|
||||||
#include <iostream>
|
|
||||||
#include <memory>
|
|
||||||
#include <mutex>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
template<typename STREAM, typename PrinterType>
|
|
||||||
class Printer {
|
|
||||||
private:
|
|
||||||
PrinterType* const type_ptr = static_cast<PrinterType*>(this);
|
|
||||||
|
|
||||||
protected:
|
|
||||||
STREAM& _stream;
|
|
||||||
Printer(STREAM* const stream_) : _stream(stream_) {}
|
|
||||||
|
|
||||||
public:
|
|
||||||
template<typename T>
|
|
||||||
PrinterType& operator<<(const T& val_) {
|
|
||||||
(*type_ptr) << val_;
|
|
||||||
return type_ptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
class Terminal : public Printer<decltype(std::cout), Terminal> {
|
|
||||||
private:
|
|
||||||
Terminal* const type_ptr = static_cast<Terminal*>(this);
|
|
||||||
using MutexLock = std::lock_guard<std::mutex>;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Base = Printer<decltype(std::cout), Terminal>;
|
|
||||||
using Base::_stream;
|
|
||||||
std::mutex _mutex;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
Terminal& operator<<(const T& val_) {
|
|
||||||
MutexLock lock(_mutex);
|
|
||||||
_stream << val_;
|
|
||||||
return *type_ptr;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#endif // _NB_PRINTER
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_STRING_UTILS
|
|
||||||
#define _NB_STRING_UTILS
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
#include <string_view>
|
|
||||||
|
|
||||||
#include <NBCore/TypeTraits.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
#ifdef _NB_TARGET_WINDOWS
|
|
||||||
inline static const std::string NEWLINE = "\n";
|
|
||||||
inline static const std::wstring WNEWLINE = L"\n";
|
|
||||||
#endif // _NB_TARGET_WINDOWS
|
|
||||||
#ifdef _NB_TARGET_LINUX
|
|
||||||
inline const std::string NEWLINE = "\n";
|
|
||||||
inline const std::wstring WNEWLINE = L"\n";
|
|
||||||
#endif // _NB_TARGET_LINUX
|
|
||||||
|
|
||||||
const std::string TABOVER = " ";
|
|
||||||
|
|
||||||
template <typename T = char>
|
|
||||||
std::basic_string<T> find_and_replace(
|
|
||||||
ExplicitType_t<std::basic_string<T>> original,
|
|
||||||
ExplicitType_t<std::basic_string_view<T>> find,
|
|
||||||
ExplicitType_t<std::basic_string_view<T>> replace
|
|
||||||
) {
|
|
||||||
using StringType = std::basic_string<T>;
|
|
||||||
|
|
||||||
StringType ret(original);
|
|
||||||
|
|
||||||
std::size_t find_len = find.length();
|
|
||||||
std::size_t replace_len = replace.length();
|
|
||||||
std::size_t currpos = 0;
|
|
||||||
while(true) {
|
|
||||||
currpos = ret.find(find, currpos);
|
|
||||||
if (currpos == StringType::npos) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
ret = ret.erase(currpos, find_len);
|
|
||||||
ret = ret.insert(currpos, replace);
|
|
||||||
currpos += replace_len;
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string indent_strblock(
|
|
||||||
std::string block,
|
|
||||||
std::string prepend,
|
|
||||||
std::string topIndent
|
|
||||||
);
|
|
||||||
|
|
||||||
std::string indent_strblock(
|
|
||||||
std::string block,
|
|
||||||
std::string prepend
|
|
||||||
);
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#endif // _NB_STRING_UTILS
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_TYPE_TRAITS
|
|
||||||
#define _NB_TYPE_TRAITS
|
|
||||||
|
|
||||||
#include <type_traits>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
namespace detail {
|
|
||||||
template <
|
|
||||||
class Default,
|
|
||||||
class AlwaysVoid,
|
|
||||||
template <class...> class Op,
|
|
||||||
class... Args
|
|
||||||
>
|
|
||||||
struct detector {
|
|
||||||
using value = std::false_type;
|
|
||||||
using type = Default;
|
|
||||||
};
|
|
||||||
|
|
||||||
template <
|
|
||||||
class Default,
|
|
||||||
template <class...> class Op,
|
|
||||||
class... Args
|
|
||||||
>
|
|
||||||
struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> {
|
|
||||||
using value = std::true_type;
|
|
||||||
using type = Op<Args...>;
|
|
||||||
};
|
|
||||||
} // namespace detail
|
|
||||||
|
|
||||||
enum TypeCodes {
|
|
||||||
UINT8, UINT16, UINT32, UINT64, INT8, INT16, INT32, INT64,
|
|
||||||
FLOAT16, FLOAT32, DOUBLE64, BOOL, NONE
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
static constexpr TypeCodes GetTypeEnum = NONE;
|
|
||||||
|
|
||||||
struct NoneType{};
|
|
||||||
|
|
||||||
template<typename T, unsigned int Arg>
|
|
||||||
using Const_t = std::integral_constant<T, Arg>;
|
|
||||||
|
|
||||||
template <
|
|
||||||
template <class...> class Op,
|
|
||||||
class... Args
|
|
||||||
>
|
|
||||||
using is_detected = typename detail::detector<NoneType, void, Op, Args...>::value;
|
|
||||||
|
|
||||||
template <typename... Types>
|
|
||||||
struct ValidConversion;
|
|
||||||
|
|
||||||
template <typename To, typename A, typename B, typename... Rest>
|
|
||||||
struct ValidConversion<To, A, B, Rest...> {
|
|
||||||
typedef std::conjunction<
|
|
||||||
std::is_constructible<To, A>, std::is_constructible<To, A>, std::conjunction<std::is_constructible<To, Rest>...>
|
|
||||||
> value_type;
|
|
||||||
static constexpr bool value = value_type::value;
|
|
||||||
typedef std::enable_if_t<value, To> to;
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename To, typename From>
|
|
||||||
struct ValidConversion<To, From> {
|
|
||||||
typedef std::is_constructible<To, From> value_type;
|
|
||||||
static constexpr bool value = value_type::value;
|
|
||||||
typedef std::enable_if_t<value, To> to;
|
|
||||||
typedef std::enable_if_t<value, From> from;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename... Types>
|
|
||||||
using ValidConversion_v = typename ValidConversion<Types...>::value;
|
|
||||||
|
|
||||||
template<typename... Types>
|
|
||||||
using ValidConversion_to = typename ValidConversion<Types...>::to;
|
|
||||||
|
|
||||||
template<typename To, typename From>
|
|
||||||
using ValidConversion_from = typename ValidConversion<To, From>::from;
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
struct ExplicitType { using type=T; };
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
using ExplicitType_t = typename ExplicitType<T>::type;
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
T* NULLPTR = static_cast<T*>(nullptr);
|
|
||||||
|
|
||||||
template <typename Func, typename T>
|
|
||||||
struct RunAndOutput {
|
|
||||||
using type = T;
|
|
||||||
T value;
|
|
||||||
RunAndOutput(Func func, T val) : value(val) {
|
|
||||||
func();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T, typename... Pack>
|
|
||||||
struct Find;
|
|
||||||
|
|
||||||
template<typename T, typename U, typename... Pack>
|
|
||||||
struct Find<T, U, Pack...> {
|
|
||||||
protected:
|
|
||||||
using here = Find<T, U>;
|
|
||||||
static constexpr unsigned int downstream = std::conditional_t<
|
|
||||||
here::value,
|
|
||||||
Const_t<unsigned int, 0>,
|
|
||||||
Find<T, Pack...>
|
|
||||||
>::value;
|
|
||||||
|
|
||||||
public:
|
|
||||||
static constexpr unsigned int value = std::conditional_t<
|
|
||||||
here::value,
|
|
||||||
Const_t<unsigned int, 1>,
|
|
||||||
std::conditional_t<
|
|
||||||
downstream,
|
|
||||||
Const_t<unsigned int, 1+downstream>,
|
|
||||||
Const_t<unsigned int, 0>
|
|
||||||
>
|
|
||||||
>::value;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T, typename U>
|
|
||||||
struct Find<T, U> {
|
|
||||||
public:
|
|
||||||
static constexpr unsigned int value = std::conditional_t<
|
|
||||||
std::is_base_of<T, U>::value,
|
|
||||||
std::integral_constant<unsigned int, 1>,
|
|
||||||
std::integral_constant<unsigned int, 0>
|
|
||||||
>::value;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
#endif // _NB_TYPE_TRAITS
|
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_CORE_TYPES
|
|
||||||
#define _NB_CORE_TYPES
|
|
||||||
|
|
||||||
#include <memory>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
// #include <NBCore/Errors.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
template<typename A, typename B>
|
|
||||||
class ConstantMap : public std::unordered_map<A, B> {
|
|
||||||
using Base = std::unordered_map<A, B>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
using Base::at;
|
|
||||||
const B& operator[](const A& key) const {
|
|
||||||
return at(key);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
using SharedVector = std::vector<std::shared_ptr<T>>;
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
using RValueVector = std::vector<T&&>;
|
|
||||||
|
|
||||||
using ByteVector = std::vector<uint8_t>;
|
|
||||||
|
|
||||||
/* class ObjectManagerError : public Error<ObjectManagerError> {
|
|
||||||
using Base = Error<ObjectManagerError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, NO_MANAGER, MANAGER_MISMATCH, LOCK_OVERFLOW, BAD_THREAD
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
}; */
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
ByteVector vectorToBytes(const std::vector<T>& vec) {
|
|
||||||
unsigned int num_bytes = vec.size() * sizeof(T);
|
|
||||||
ByteVector ret(num_bytes);
|
|
||||||
memcpy(ret.data(), vec.data(), num_bytes);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T, typename S>
|
|
||||||
ByteVector concatVectorBytes(const std::vector<T>& vec1, const std::vector<S>& vec2) {
|
|
||||||
ByteVector vec1_raw = vectorToBytes<T>(vec1);
|
|
||||||
ByteVector vec2_raw = vectorToBytes<S>(vec2);
|
|
||||||
unsigned int vec1_raw_size = vec1_raw.size();
|
|
||||||
unsigned int vec2_raw_size = vec2_raw.size();
|
|
||||||
ByteVector ret(vec1_raw_size + vec2_raw_size);
|
|
||||||
memcpy(ret.data(), vec1_raw.data(), vec1_raw_size);
|
|
||||||
memcpy(ret.data() + vec1_raw_size, vec2_raw.data(), vec2_raw_size);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
std::vector<T> bytesToVector(const ByteVector& vec) {
|
|
||||||
if (vec.size() % sizeof(T) != 0) {
|
|
||||||
/* THROW(Error<NoneType>(
|
|
||||||
std::runtime_error("Data size does not align to std::vector<" + std::string(typeid(T).name()) + ">.")
|
|
||||||
)); */
|
|
||||||
throw "byyyyeeee";
|
|
||||||
}
|
|
||||||
unsigned int num_elmts = vec.size() / sizeof(T);
|
|
||||||
std::vector<T> ret(num_elmts);
|
|
||||||
memcpy(ret.data(), vec.data(), vec.size());
|
|
||||||
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* template <typename T>
|
|
||||||
class ThreadsafeObjectLock;
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
class ThreadsafeObject {
|
|
||||||
using Codes = ObjectManagerError::Codes;
|
|
||||||
|
|
||||||
public:
|
|
||||||
ThreadsafeObject(T&& obj)
|
|
||||||
: _obj(std::make_shared<T>(obj)) {}
|
|
||||||
|
|
||||||
ThreadsafeObjectLock<T> lock() {
|
|
||||||
return ThreadsafeObjectLock<T>(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
friend ThreadsafeObjectLock<T>;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
std::shared_ptr<T> _obj;
|
|
||||||
mutable std::recursive_mutex _mutex;
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
class ThreadsafeObjectLock {
|
|
||||||
public:
|
|
||||||
ThreadsafeObjectLock(const ThreadsafeObjectLock&) = delete;
|
|
||||||
ThreadsafeObjectLock operator=(const ThreadsafeObjectLock&) = delete;
|
|
||||||
~ThreadsafeObjectLock() {
|
|
||||||
_manager->_mutex.unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
T* operator->() {
|
|
||||||
return _manager->_obj.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
friend ThreadsafeObject<T>;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
ThreadsafeObjectLock(
|
|
||||||
ThreadsafeObject<T>* const manager_
|
|
||||||
) : _manager(manager_) {
|
|
||||||
if (!_manager) {
|
|
||||||
using Codes = ObjectManagerError::Codes;
|
|
||||||
THROW(ObjectManagerError(Codes::NO_MANAGER));
|
|
||||||
}
|
|
||||||
_manager->_mutex.lock();
|
|
||||||
}
|
|
||||||
ThreadsafeObject<T>* const _manager;
|
|
||||||
}; */
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#endif // _NB_CORE_TYPES
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#include "Errors.hpp"
|
||||||
|
#include "TypeTraits.hpp"
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
const std::string Error<nb::NoneType>::type = "nb::Error";
|
||||||
|
|
||||||
|
const ErrorCodeMap Error<nb::NoneType>::ErrorMessages = {
|
||||||
|
{Error::Codes::GENERAL, "General std::exception."},
|
||||||
|
{Error::Codes::UNDEFINED, "Undefined / general error."},
|
||||||
|
{Error::Codes::BADERRORCODE, "Unrecognized error code."}
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
#include <NBCore/ErrorsImpl.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
//ErrorBase::
|
|
||||||
ErrorBase::ErrorBase(const std::exception& exception_) noexcept
|
|
||||||
: ErrorBase(Error(exception_)) {}
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,82 +1,15 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <sstream>
|
|
||||||
|
|
||||||
#include <NBCore/Logger.hpp>
|
#include "Logger.hpp"
|
||||||
#include <NBCore/StringUtils.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
namespace nb {
|
||||||
|
|
||||||
static bool RUN_LOGGER(nb::DefaultDebugLogger& logger_) {
|
nb::DefaultDebugLogger logger(std::cout);
|
||||||
logger_.run();
|
|
||||||
return logger_.isRunning();
|
static bool RUN_LOGGER(nb::DefaultDebugLogger& log) {
|
||||||
|
return log.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef _NB_AUTOLOG
|
static const bool LOGGER_RUNNING = RUN_LOGGER(logger);
|
||||||
DefaultDebugLogger logger({std::static_pointer_cast<LogEventHandler>(
|
|
||||||
std::make_shared<DefaultTerminalLogEventPrinter>(0x0)
|
|
||||||
)});
|
|
||||||
const bool LOGGER_RUNNING = RUN_LOGGER(logger);
|
|
||||||
#else
|
|
||||||
const bool LOGGER_RUNNING = false;
|
|
||||||
#endif // _NB_AUTOLOG
|
|
||||||
|
|
||||||
// class LogEventHandler
|
|
||||||
|
|
||||||
LogEventHandler::LogEventHandler(uint8_t logging_level) {
|
|
||||||
_logLevel.store(logging_level, std::memory_order_release);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool LogEventHandler::stop() noexcept {
|
|
||||||
_running.store(false, std::memory_order_release);
|
|
||||||
return isRunning();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool LogEventHandler::run() {
|
|
||||||
_running.store(true, std::memory_order_release);
|
|
||||||
return isRunning();
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t LogEventHandler::logLevel(uint8_t val) {
|
|
||||||
_logLevel.store(val, std::memory_order_release);
|
|
||||||
return logLevel();
|
|
||||||
}
|
|
||||||
uint8_t LogEventHandler::logLevel() const {
|
|
||||||
return _logLevel.load();
|
|
||||||
}
|
|
||||||
|
|
||||||
// class DefaultTerminalLogEventPrinter
|
|
||||||
|
|
||||||
bool DefaultTerminalLogEventPrinter::in(const LogEvent& msg) {
|
|
||||||
if (!isRunning()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (msg.lvl < logLevel()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
constexpr size_t level_field_width = 5;
|
|
||||||
constexpr size_t msg_prompt_length = level_field_width+7;
|
|
||||||
std::stringstream formatted_stream;
|
|
||||||
formatted_stream << "[";
|
|
||||||
formatted_stream.width(level_field_width);
|
|
||||||
formatted_stream << std::to_string(msg.lvl) << "] :: ";
|
|
||||||
std::string fileloc="";
|
|
||||||
if (!msg.file.empty()) {
|
|
||||||
fileloc += "(" + msg.file + ":" + std::to_string(msg.line) + ") - ";
|
|
||||||
}
|
|
||||||
formatted_stream << indent_strblock(
|
|
||||||
fileloc + msg.msg,
|
|
||||||
std::string(20 - msg_prompt_length, ' '),
|
|
||||||
""
|
|
||||||
) << nb::NEWLINE;
|
|
||||||
std::string formatted_string = formatted_stream.str();
|
|
||||||
std::cout << formatted_string << std::flush;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// class DefaultDebugLogger
|
|
||||||
|
|
||||||
bool DefaultDebugLogger::process(const LogEvent& msg) {
|
|
||||||
return _logsink->in(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace nb
|
} // namespace nb
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
#endif // _NB_TARGET_LINUX
|
#endif // _NB_TARGET_LINUX
|
||||||
|
|
||||||
#include <NBCore/Processes.hpp>
|
#include "Processes.hpp"
|
||||||
|
|
||||||
namespace nb {
|
namespace nb {
|
||||||
|
|
||||||
@@ -15,17 +15,8 @@ uint64_t GetPID() {
|
|||||||
return GetCurrentProcessId();
|
return GetCurrentProcessId();
|
||||||
}
|
}
|
||||||
#endif // _NB_TARGET_WINDOWS
|
#endif // _NB_TARGET_WINDOWS
|
||||||
|
|
||||||
#ifdef _NB_TARGET_LINUX
|
#ifdef _NB_TARGET_LINUX
|
||||||
#endif // _NB_TARGET_LINUX
|
#endif // _NB_TARGET_LINUX
|
||||||
|
|
||||||
#ifdef _NB_TARGET_WINDOWS
|
|
||||||
uint64_t GetTID() {
|
|
||||||
return GetCurrentThreadId();
|
|
||||||
}
|
|
||||||
#endif // _NB_TARGET_WINDOWS
|
|
||||||
#ifdef _NB_TARGET_LINUX
|
|
||||||
#endif // _NB_TARGET_LINUX
|
|
||||||
|
|
||||||
thread_local const uint64_t CurrentTID = GetTID();
|
|
||||||
|
|
||||||
} // namespace nb
|
} // namespace nb
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
#include <NBCore/StringUtils.hpp>
|
|
||||||
|
|
||||||
/* std::string nb::wstr_to_str(std::wstring in) {
|
|
||||||
std::size_t wstrlen = in.length();
|
|
||||||
char* c_str= new char[wstrlen];
|
|
||||||
std::wcstombs(c_str, in.c_str(), wstrlen);
|
|
||||||
std::string ret(c_str, wstrlen);
|
|
||||||
delete[] c_str;
|
|
||||||
return ret;
|
|
||||||
} */
|
|
||||||
|
|
||||||
std::string nb::indent_strblock(
|
|
||||||
std::string block,
|
|
||||||
std::string prepend,
|
|
||||||
std::string topIndent
|
|
||||||
) {
|
|
||||||
return topIndent + nb::find_and_replace(
|
|
||||||
block,
|
|
||||||
nb::NEWLINE,
|
|
||||||
nb::NEWLINE + prepend
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string nb::indent_strblock(
|
|
||||||
std::string block,
|
|
||||||
std::string prepend
|
|
||||||
) {
|
|
||||||
return nb::indent_strblock(block, prepend, prepend);
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
#include <NBCore/TypeTraits.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<unsigned char> = TypeCodes::UINT8;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<unsigned short> = TypeCodes::UINT16;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<unsigned int> = TypeCodes::UINT32;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<unsigned long int> = TypeCodes::UINT64;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<char> = TypeCodes::INT8;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<short> = TypeCodes::INT16;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<int> = TypeCodes::INT32;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<long> = TypeCodes::INT64;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<float> = TypeCodes::FLOAT32;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<double> = TypeCodes::DOUBLE64;
|
|
||||||
template<> constexpr TypeCodes GetTypeEnum<bool> = TypeCodes::BOOL;
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
@@ -1,27 +1,8 @@
|
|||||||
#include <NBCore/Utils.hpp>
|
#include <string>
|
||||||
|
#include "Utils.hpp"
|
||||||
|
|
||||||
namespace nb {
|
template<>
|
||||||
|
std::wstring nb::str_to_wstr(const std::string& in) {
|
||||||
/* using ObjectManagerCodes = ObjectManagerError::Codes;
|
std::wstring ret(in.begin(), in.end());
|
||||||
const std::string ObjectManagerError::type = "nb::ObjectManagerError";
|
return ret;
|
||||||
const ErrorCodeMap ObjectManagerError::ErrorMessages({
|
}
|
||||||
{ObjectManagerCodes::UNDEFINED, "Error"},
|
|
||||||
{
|
|
||||||
ObjectManagerCodes::NO_MANAGER,
|
|
||||||
"Attempting to create object lock without lock manager"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
ObjectManagerCodes::MANAGER_MISMATCH,
|
|
||||||
"Attempting to delete object lock from mismatched lock manager"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
ObjectManagerCodes::LOCK_OVERFLOW,
|
|
||||||
"Too many object locks allocated"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
ObjectManagerCodes::BAD_THREAD,
|
|
||||||
"Attempting operation from a bad thread"
|
|
||||||
}
|
|
||||||
}); */
|
|
||||||
|
|
||||||
}; // namespace nb
|
|
||||||
|
|||||||
@@ -12,13 +12,5 @@ if (NB_BUILD_TESTS)
|
|||||||
NBCore
|
NBCore
|
||||||
GTest::gtest_main
|
GTest::gtest_main
|
||||||
)
|
)
|
||||||
|
|
||||||
add_executable(LoggerTest
|
|
||||||
./testLogger.cpp
|
|
||||||
)
|
|
||||||
target_link_libraries(LoggerTest
|
|
||||||
NBCore
|
|
||||||
)
|
|
||||||
|
|
||||||
gtest_discover_tests(TestCore)
|
gtest_discover_tests(TestCore)
|
||||||
endif()
|
endif()
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
#define CODE_ERROR_LOCATIONS
|
#define CODE_ERROR_LOCATIONS
|
||||||
|
|
||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
#include <string>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
#include "Errors.hpp"
|
||||||
|
#include <string>
|
||||||
|
#include "Utils.hpp"
|
||||||
|
|
||||||
using namespace nb;
|
using namespace nb;
|
||||||
|
|
||||||
@@ -35,5 +36,5 @@ const ErrorCodeMap TestError::ErrorMessages{
|
|||||||
|
|
||||||
TEST(ErrorTest, Test) {
|
TEST(ErrorTest, Test) {
|
||||||
auto err = TestError(0, TestError(1, TestError(2, TestError(3, TestError(2)))));
|
auto err = TestError(0, TestError(1, TestError(2, TestError(3, TestError(2)))));
|
||||||
ASSERT_STREQ(err.what().c_str(), "Hey!\n Trace: How\n Trace: You\n Trace: Doin\n Trace: You");
|
ASSERT_STREQ(err.what(), "Hey!\n Trace: How\n Trace: You\n Trace: Doin\n Trace: You\n");
|
||||||
}
|
}
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
#define _NB_AUTOLOG
|
|
||||||
#include <exception>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
#include <NBCore/Logger.hpp>
|
|
||||||
|
|
||||||
class TestError : public nb::Error<TestError> {
|
|
||||||
using Base = Error<TestError>;
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
using Base::what;
|
|
||||||
using Base::code;
|
|
||||||
using Base::msg;
|
|
||||||
using Base::trace;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
A, B, C, D
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const nb::ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
const std::string TestError::type="TestError";
|
|
||||||
const nb::ErrorCodeMap TestError::ErrorMessages{
|
|
||||||
{TestError::Codes::A, "Hey!"},
|
|
||||||
{TestError::Codes::B, "How"},
|
|
||||||
{TestError::Codes::C, "You"},
|
|
||||||
{TestError::Codes::D, "Doin"}
|
|
||||||
};
|
|
||||||
|
|
||||||
int main() {
|
|
||||||
while(!nb::LOGGER_RUNNING) {}
|
|
||||||
nb::logger.minimalLogLevel(0x0);
|
|
||||||
nb::logger.msg("Whoop!");
|
|
||||||
try {
|
|
||||||
THROW(TestError(0, TestError(1, TestError(2, TestError(3, TestError(2))))));
|
|
||||||
} catch (TestError e){
|
|
||||||
nb::logger.msg("nb::Error was thrown!");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
THROW(std::exception());
|
|
||||||
} catch (std::exception e){
|
|
||||||
nb::logger.msg("std::exception was thrown!");
|
|
||||||
}
|
|
||||||
ERROR("hello there!");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
#define CODE_ERROR_LOCATIONS
|
#define CODE_ERROR_LOCATIONS
|
||||||
|
|
||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
#include <NBCore/Processes.hpp>
|
#include "Processes.hpp"
|
||||||
#include <Windows.h>
|
#include <Windows.h>
|
||||||
|
|
||||||
TEST(ProcessesTest, GetPID) {
|
TEST(ProcessesTest, GetPID) {
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <NBCore/TypeTraits.hpp>
|
#include "TypeTraits.hpp"
|
||||||
#include <NBCore/StringUtils.hpp>
|
#include "Utils.hpp"
|
||||||
|
|
||||||
namespace nb {
|
namespace nb {
|
||||||
|
|
||||||
@@ -43,38 +43,38 @@ TEST(UtilsTest, TestFindAndReplace) {
|
|||||||
|
|
||||||
TEST(UtilsTest, TestFindAndReplaceWstr) {
|
TEST(UtilsTest, TestFindAndReplaceWstr) {
|
||||||
ASSERT_STREQ(
|
ASSERT_STREQ(
|
||||||
find_and_replace<wchar_t>(L"Jeff", L"e", L"efe").c_str(),
|
find_and_replace<std::wstring>(L"Jeff", L"e", L"efe").c_str(),
|
||||||
L"Jefeff"
|
L"Jefeff"
|
||||||
);
|
);
|
||||||
|
|
||||||
std::wstring tmp = find_and_replace<wchar_t>(L"Naif", L"a", L"afa");
|
std::wstring tmp = find_and_replace<std::wstring>(L"Naif", L"a", L"afa");
|
||||||
ASSERT_STREQ(
|
ASSERT_STREQ(
|
||||||
find_and_replace<wchar_t>(tmp, L"i", L"ifi").c_str(),
|
find_and_replace<std::wstring>(tmp, L"i", L"ifi").c_str(),
|
||||||
L"Nafaifif"
|
L"Nafaifif"
|
||||||
);
|
);
|
||||||
|
|
||||||
tmp = find_and_replace<wchar_t>(L"aeiou", L"a", L"afa");
|
tmp = find_and_replace<std::wstring>(L"aeiou", L"a", L"afa");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"e", L"efe");
|
tmp = find_and_replace<std::wstring>(tmp, L"e", L"efe");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"i", L"ifi");
|
tmp = find_and_replace<std::wstring>(tmp, L"i", L"ifi");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"o", L"ofo");
|
tmp = find_and_replace<std::wstring>(tmp, L"o", L"ofo");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"u", L"ufu");
|
tmp = find_and_replace<std::wstring>(tmp, L"u", L"ufu");
|
||||||
ASSERT_STREQ(
|
ASSERT_STREQ(
|
||||||
tmp.c_str(),
|
tmp.c_str(),
|
||||||
L"afaefeifiofoufu"
|
L"afaefeifiofoufu"
|
||||||
);
|
);
|
||||||
|
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"afa", L"a");
|
tmp = find_and_replace<std::wstring>(tmp, L"afa", L"a");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"efe", L"e");
|
tmp = find_and_replace<std::wstring>(tmp, L"efe", L"e");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"ifi", L"i");
|
tmp = find_and_replace<std::wstring>(tmp, L"ifi", L"i");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"ofo", L"o");
|
tmp = find_and_replace<std::wstring>(tmp, L"ofo", L"o");
|
||||||
tmp = find_and_replace<wchar_t>(tmp, L"ufu", L"u");
|
tmp = find_and_replace<std::wstring>(tmp, L"ufu", L"u");
|
||||||
ASSERT_STREQ(
|
ASSERT_STREQ(
|
||||||
tmp.c_str(),
|
tmp.c_str(),
|
||||||
L"aeiou"
|
L"aeiou"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* TEST(UtilsTest, TestWstrToStr) {
|
TEST(UtilsTest, TestWstrToStr) {
|
||||||
ASSERT_STREQ(
|
ASSERT_STREQ(
|
||||||
nb::wstr_to_str(L"Hi!").c_str(),
|
nb::wstr_to_str(L"Hi!").c_str(),
|
||||||
"Hi!"
|
"Hi!"
|
||||||
@@ -91,9 +91,9 @@ TEST(UtilsTest, TestFindAndReplaceWstr) {
|
|||||||
nb::wstr_to_str(L"Naif\ttalks\r\ra\t\nlot").c_str(),
|
nb::wstr_to_str(L"Naif\ttalks\r\ra\t\nlot").c_str(),
|
||||||
"Naif\ttalks\r\ra\t\nlot"
|
"Naif\ttalks\r\ra\t\nlot"
|
||||||
);
|
);
|
||||||
} */
|
}
|
||||||
|
|
||||||
/* TEST(UtilsTest, TestStrToWstr) {
|
TEST(UtilsTest, TestStrToWstr) {
|
||||||
ASSERT_STREQ(
|
ASSERT_STREQ(
|
||||||
nb::str_to_wstr("Hi!").c_str(),
|
nb::str_to_wstr("Hi!").c_str(),
|
||||||
L"Hi!"
|
L"Hi!"
|
||||||
@@ -110,7 +110,7 @@ TEST(UtilsTest, TestFindAndReplaceWstr) {
|
|||||||
nb::str_to_wstr("Naif\ttalks\r\ra\t\nlot").c_str(),
|
nb::str_to_wstr("Naif\ttalks\r\ra\t\nlot").c_str(),
|
||||||
L"Naif\ttalks\r\ra\t\nlot"
|
L"Naif\ttalks\r\ra\t\nlot"
|
||||||
);
|
);
|
||||||
} */
|
}
|
||||||
|
|
||||||
struct A { bool x(); };
|
struct A { bool x(); };
|
||||||
struct B { bool y(); };
|
struct B { bool y(); };
|
||||||
|
|||||||
@@ -1,70 +0,0 @@
|
|||||||
cmake_minimum_required(VERSION 3.10)
|
|
||||||
project(NBData VERSION 0.1)
|
|
||||||
|
|
||||||
include(GNUInstallDirs)
|
|
||||||
include(CMakePackageConfigHelpers)
|
|
||||||
|
|
||||||
toAbsolutePath(NB_DATA_SOURCE
|
|
||||||
./src/FFT.cpp
|
|
||||||
)
|
|
||||||
toAbsolutePath(NB_DATA_INCLUDE
|
|
||||||
./include/NBData/FFT.hpp
|
|
||||||
)
|
|
||||||
|
|
||||||
set(NB_DATA_SOURCE ${NB_DATA_SOURCE} PARENT_SCOPE)
|
|
||||||
set(NB_DATA_INCLUDE ${NB_DATA_INCLUDE} PARENT_SCOPE)
|
|
||||||
|
|
||||||
add_library(NBData ${NB_DATA_SOURCE})
|
|
||||||
add_library(NBEngine::Data ALIAS NBData)
|
|
||||||
target_link_libraries(NBData
|
|
||||||
NBCore
|
|
||||||
)
|
|
||||||
target_include_directories(NBData
|
|
||||||
PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
|
|
||||||
PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
|
|
||||||
)
|
|
||||||
export(
|
|
||||||
TARGETS NBData
|
|
||||||
FILE "${CMAKE_BINARY_DIR}/cmake/NBDataTargets.cmake"
|
|
||||||
NAMESPACE NBEngine::
|
|
||||||
)
|
|
||||||
configure_package_config_file(
|
|
||||||
"NBDataConfig.cmake.in"
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBDataConfig.cmake"
|
|
||||||
INSTALL_DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
|
|
||||||
PATH_VARS CMAKE_INSTALL_LIBDIR
|
|
||||||
)
|
|
||||||
write_basic_package_version_file(
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBDataConfigVersion.cmake"
|
|
||||||
COMPATIBILITY AnyNewerVersion
|
|
||||||
)
|
|
||||||
|
|
||||||
if (NBENGINE_INSTALL)
|
|
||||||
message("Installing NBData to ${CMAKE_INSTALL_PREFIX}")
|
|
||||||
install(
|
|
||||||
TARGETS NBData
|
|
||||||
EXPORT NBDataTargets
|
|
||||||
LIBRARY DESTINATION lib
|
|
||||||
ARCHIVE DESTINATION lib
|
|
||||||
INCLUDES DESTINATION include
|
|
||||||
)
|
|
||||||
install(
|
|
||||||
DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/NBData"
|
|
||||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
|
|
||||||
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
|
|
||||||
)
|
|
||||||
install(
|
|
||||||
EXPORT NBDataTargets
|
|
||||||
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
|
|
||||||
NAMESPACE NBEngine::
|
|
||||||
)
|
|
||||||
install(FILES
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBDataConfig.cmake"
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBDataConfigVersion.cmake"
|
|
||||||
DESTINATION "${CMAKE_INSTALL_PREFIX}/CMake"
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
if (NB_BUILD_TESTS)
|
|
||||||
add_subdirectory(./tests )
|
|
||||||
endif()
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
@PACKAGE_INIT@
|
|
||||||
include("${CMAKE_CURRENT_LIST_DIR}/NBDataTargets.cmake")
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_DATA_FFT
|
|
||||||
#define _NB_DATA_FFT
|
|
||||||
|
|
||||||
#include <cmath>
|
|
||||||
#include <complex>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
|
|
||||||
#ifndef PI_VALUE
|
|
||||||
#define PI_VALUE 3.1415926535
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*! @file FFT.hpp */
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
using namespace std::complex_literals;
|
|
||||||
|
|
||||||
constexpr double operator""_pi(long double val) {
|
|
||||||
return val*PI_VALUE;
|
|
||||||
}
|
|
||||||
constexpr double operator""_pi(unsigned long long val) {
|
|
||||||
return val*PI_VALUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
constexpr float operator""_pif(long double val) {
|
|
||||||
return val*PI_VALUE;
|
|
||||||
}
|
|
||||||
constexpr float operator""_pif(unsigned long long val) {
|
|
||||||
return val*PI_VALUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
bool isPowerOf2(const T& x) {
|
|
||||||
bool ret = false;
|
|
||||||
unsigned int mask=1;
|
|
||||||
for (int i=0; i<(8*sizeof(std::declval<T>())); ++i) {ret ^= x&mask; mask<<=1;}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*!
|
|
||||||
@brief Calculates the complex-valued twiddle factor given the `phase`
|
|
||||||
@param phase A double representing the phase, or `(k*n)/N`, of a DFT,
|
|
||||||
in units of 2*Pi.
|
|
||||||
@return A std::complex<T> representing the complex twiddle factor of
|
|
||||||
the DFT at that `phase`, calculated via `exp(-2*Pi*i*phase)`.
|
|
||||||
|
|
||||||
Calculates the complex-valued twiddle factor given the `phase` in units
|
|
||||||
of the ratio around the circle (i.e. in units of 2*Pi), calculated via
|
|
||||||
`exp(-2*Pi*i*phase)`. Note the minus sign, as this function is for the
|
|
||||||
*forward* DFT.
|
|
||||||
*/
|
|
||||||
template<typename T>
|
|
||||||
std::complex<T> calculateTwiddleFactor(double phase) {
|
|
||||||
int sign = -1;
|
|
||||||
while(phase>0.5) { phase-=0.5; sign*=-1; }
|
|
||||||
return static_cast<std::complex<T>>(std::exp(2_pi*(sign)*(1i)*phase));
|
|
||||||
}
|
|
||||||
|
|
||||||
/*!
|
|
||||||
Stores the twiddle factors for Radix-2 DFT matrices for a given data type
|
|
||||||
(i.e. stores std::complex<T> values), which can be retrieved using `TwiddleFactor<T>::get`.
|
|
||||||
*/
|
|
||||||
template<typename T>
|
|
||||||
class TwiddleFactors2 {
|
|
||||||
protected:
|
|
||||||
static std::unordered_map<unsigned int, std::complex<T>> factors;
|
|
||||||
|
|
||||||
public:
|
|
||||||
/*!
|
|
||||||
@brief Retrieves the twiddle factor for a Radix-2 DFT
|
|
||||||
@param numerator The numerator (i.e. `k*n` of a DFT matrix) part of the phase
|
|
||||||
when defined in units of 2*Pi.
|
|
||||||
@param log2N The `log2(denominator)` (i.e. `/N` of a DFT matrix) part of the phase
|
|
||||||
when defined in units of 2*Pi.
|
|
||||||
@return A std::complex<T> for the value of the `numerator / (2^log2N)` twiddle factor
|
|
||||||
*/
|
|
||||||
static std::complex<T> get(unsigned int numerator, unsigned int log2N);
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
std::complex<T>* fft2_impl(
|
|
||||||
const std::complex<T>* source,
|
|
||||||
std::complex<T>* dest,
|
|
||||||
unsigned int log2N,
|
|
||||||
unsigned int stride=1
|
|
||||||
) {
|
|
||||||
constexpr std::complex<T> J(0, 1);
|
|
||||||
switch(log2N) {
|
|
||||||
case 0:
|
|
||||||
dest[0] = source[0];
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 1:
|
|
||||||
dest[0] = source[0] + source[stride];
|
|
||||||
dest[1] = source[0] - source[stride];
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 2:
|
|
||||||
dest[0] = source[0] + source[stride] + source[2*stride] + source[3*stride];
|
|
||||||
dest[1] = source[0] - J*source[stride] - source[2*stride] + J*source[3*stride];
|
|
||||||
dest[2] = source[0] - source[stride] + source[2*stride] - source[3*stride];
|
|
||||||
dest[3] = source[0] + J*source[stride] - source[2*stride] - J*source[3*stride];
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
const unsigned int halfway = 1<<(log2N-1);
|
|
||||||
fft2_impl(source, dest, log2N-1, 2*stride);
|
|
||||||
fft2_impl(&(source[stride]), &(dest[halfway]), log2N-1, 2*stride);
|
|
||||||
std::complex<T> twiddle;
|
|
||||||
std::complex<T> p, q;
|
|
||||||
for (unsigned int i=0; i < halfway; ++i) {
|
|
||||||
twiddle = TwiddleFactors2<T>::get(i, log2N);
|
|
||||||
p = dest[i];
|
|
||||||
q = dest[halfway+i]*twiddle;
|
|
||||||
dest[i] = p+q;
|
|
||||||
dest[halfway+i] = p-q;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
return dest;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
std::complex<T>* dft_impl(
|
|
||||||
const std::complex<T>* source,
|
|
||||||
std::complex<T>* dest,
|
|
||||||
unsigned int N
|
|
||||||
) {
|
|
||||||
for (int k=0; k < N; ++k) {
|
|
||||||
dest[k] = 0;
|
|
||||||
for (int n = 0; n < N; ++n) {
|
|
||||||
dest[k] += source[n] * calculateTwiddleFactor<T>(double(n*k)/double(N));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return dest;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*!
|
|
||||||
@brief Computes the minimal Radix-2 DFT on a std::vector<std::complex<T>>
|
|
||||||
@param values A std::vector<std::complex<T>> representing the time domain values
|
|
||||||
@return A std::vector<std::complex<T>>, representing the minimal Radix-2 DFT of `values`
|
|
||||||
|
|
||||||
Computes the Radix-2 DFT on a std::vector<std::complex<T>>. If the input vector
|
|
||||||
`values` is not a power of 2, then the number of points in the DFT (and thus the
|
|
||||||
size of the returned frequency domain vector) is determined by
|
|
||||||
`2^ceil(log2(values.size()))`
|
|
||||||
*/
|
|
||||||
template<typename T>
|
|
||||||
std::vector<std::complex<T>> fft2(const std::vector<std::complex<T>>& values) {
|
|
||||||
const auto N = values.size();
|
|
||||||
unsigned int log2N=0;
|
|
||||||
while(1<<log2N < N) {log2N++;}
|
|
||||||
std::vector<std::complex<T>> temp(1<<log2N, 0);
|
|
||||||
std::vector<std::complex<T>> ret = temp;
|
|
||||||
for (int i=0; i < N; ++i) { temp[i] = values[i]; }
|
|
||||||
std::complex<T>* fft_results = fft2_impl(temp.data(), ret.data(), log2N);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*!
|
|
||||||
@brief Computes the minimal Radix-2 DFT on a `std::vector<T>`
|
|
||||||
@param values A std::vector<T> representing the time domain values with packed real and
|
|
||||||
imaginary parts
|
|
||||||
@return A `std::vector<T>`, representing the minimal Radix-2 DFT of `values` with packed
|
|
||||||
real and imaginary parts
|
|
||||||
@throw std::string Thrown when the size of the vector is not divisible by 2 (i.e.
|
|
||||||
there are unmatched real/imaginary pairs).
|
|
||||||
|
|
||||||
Computes the Radix-2 DFT on a std::vector<std::complex<T>>. Equivalent to
|
|
||||||
`fft2(const std::vector<std::complex<T>>)` if `values[2*i]` and `values[2*i+1]`
|
|
||||||
were mapped to the real and imaginary parts of the complex vector.
|
|
||||||
*/
|
|
||||||
template<typename T>
|
|
||||||
std::vector<T> fft2(const std::vector<T>& values) {
|
|
||||||
if (values.size()&1) {
|
|
||||||
THROW(Error<>(Error<>::VALUE_ERROR,
|
|
||||||
"Vector must be of even length to represent complex values."
|
|
||||||
));
|
|
||||||
}
|
|
||||||
std::complex<T> complex_input(values.data(), values.size()/2);
|
|
||||||
std::complex<T> complex_ret = fft2(complex_input);
|
|
||||||
return std::vector<T>(complex_ret.data(), complex_ret.size()*2);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*!
|
|
||||||
@brief Computes the DFT on a std::vector<std::complex<T>>
|
|
||||||
@param values A std::vector<std::complex<T>> representing the time domain values
|
|
||||||
@return A std::vector<std::complex<T>> of the DFT of `values` in the frequency domain
|
|
||||||
|
|
||||||
Computes the DFT of the std::vector<std::complex<T>> `values`. Does so using the
|
|
||||||
naive O(N^2) matrix-multiplication method.
|
|
||||||
*/
|
|
||||||
template<typename T>
|
|
||||||
std::vector<std::complex<T>> dft(const std::vector<std::complex<T>>& x) {
|
|
||||||
std::vector<std::complex<T>> ret = x;
|
|
||||||
std::complex<T>* fft_results = dft_impl(x.data(), ret.data(), x.size());
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*!
|
|
||||||
@brief Computes the DFT on a `std::vector<T>`
|
|
||||||
@param values A `std::vector<T>` representing the time domain values with packed real and
|
|
||||||
imaginary parts
|
|
||||||
@return A `std::vector<T>` of the DFT of `values` in the frequency domain with
|
|
||||||
packed real and imaginary parts
|
|
||||||
@throw std::string Thrown when the size of the vector is not divisible by 2 (i.e.
|
|
||||||
there are unmatched real/imaginary pairs).
|
|
||||||
|
|
||||||
Computes the DFT on a `std::vector<T>`. Equivalent to
|
|
||||||
`dft(const std::vector<std::complex<T>>)` if `values[2*i]` and `values[2*i+1]`
|
|
||||||
were mapped to the real and imaginary parts of the complex vector.
|
|
||||||
*/
|
|
||||||
template<typename T>
|
|
||||||
std::vector<T> dft(const std::vector<T>& values) {
|
|
||||||
if (values.size()&1) {
|
|
||||||
THROW(Error<>(Error<>::VALUE_ERROR,
|
|
||||||
"Vector must be of even length to represent complex values."
|
|
||||||
));
|
|
||||||
}
|
|
||||||
std::complex<T> complex_input(values.data(), values.size()/2);
|
|
||||||
std::complex<T> complex_ret = dft(complex_input);
|
|
||||||
return std::vector<T>(complex_ret.data(), complex_ret.size()*2);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
std::unordered_map<unsigned int, std::complex<T>> TwiddleFactors2<T>::factors = {};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
std::complex<T> TwiddleFactors2<T>::get(unsigned int a, unsigned int log2N) {
|
|
||||||
while(a && !(a&1)) { a>>=1; log2N--; }
|
|
||||||
const unsigned int N = 1<<log2N;
|
|
||||||
const double phase = double(a)/double(N);
|
|
||||||
const unsigned int key = a*N;
|
|
||||||
try {
|
|
||||||
return factors.at(key);
|
|
||||||
} catch (const std::out_of_range& e) {
|
|
||||||
if (a > N>>1 ) {
|
|
||||||
return (factors[key] = std::conj(TwiddleFactors2<T>::get(N-a, log2N)));
|
|
||||||
} else {
|
|
||||||
return (factors[key] = calculateTwiddleFactor<T>(phase));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace n
|
|
||||||
|
|
||||||
#endif // _NB_DATA_FFT
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
#include <NBCore/Errors.hpp>
|
|
||||||
#include <NBData/FFT.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
cmake_minimum_required(VERSION 3.26.0)
|
|
||||||
|
|
||||||
if (NB_BUILD_TESTS)
|
|
||||||
enable_testing()
|
|
||||||
include(GoogleTest)
|
|
||||||
|
|
||||||
add_executable(TestData
|
|
||||||
./testFFT.cpp
|
|
||||||
)
|
|
||||||
target_link_libraries(TestData
|
|
||||||
NBData
|
|
||||||
GTest::gtest_main
|
|
||||||
)
|
|
||||||
gtest_discover_tests(TestData)
|
|
||||||
|
|
||||||
add_executable(FFTSpeedTest
|
|
||||||
./fftspeedtest.cpp
|
|
||||||
)
|
|
||||||
target_link_libraries(FFTSpeedTest
|
|
||||||
NBData
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
#include <NBData/FFT.hpp>
|
|
||||||
|
|
||||||
int main() {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
#include <gtest/gtest.h>
|
|
||||||
|
|
||||||
#include <NBData/ComplexNumbers.hpp>
|
|
||||||
|
|
||||||
template<typename A, typename B>
|
|
||||||
void COMPLEX_EQ(const nb::Complex<A>& a, const nb::Complex<B>& b) {
|
|
||||||
ASSERT_EQ(a.r, b.r);
|
|
||||||
ASSERT_EQ(a.i, b.i);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename A, typename B>
|
|
||||||
void COMPLEX_ALMOST_EQ(const nb::Complex<A>& a, const nb::Complex<B>& b) {
|
|
||||||
ASSERT_FLOAT_EQ(a.r, b.r);
|
|
||||||
ASSERT_FLOAT_EQ(a.i, b.i);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(ComplexNumberTests, TestConstruction) {
|
|
||||||
COMPLEX_ALMOST_EQ(nb::Complex(), nb::Complex(0,0));
|
|
||||||
COMPLEX_ALMOST_EQ(nb::Complex(5.0), nb::Complex(5, 0));
|
|
||||||
COMPLEX_ALMOST_EQ(1.5_j, nb::Complex(0.0, 1.5));
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(ComplexNumberTests, TestAdd) {
|
|
||||||
auto x = nb::Complex(1.0) - nb::Complex(2.0, 1.0);
|
|
||||||
ASSERT_FLOAT_EQ(x.r, -1);
|
|
||||||
ASSERT_FLOAT_EQ(x.i, -1);
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
#include <gtest/gtest.h>
|
|
||||||
|
|
||||||
#include <NBData/FFT.hpp>
|
|
||||||
|
|
||||||
using namespace nb;
|
|
||||||
|
|
||||||
template<typename A, typename B>
|
|
||||||
void COMPLEX_EQ(const std::complex<A>& a, const std::complex<B>& b) {
|
|
||||||
ASSERT_EQ(a.real(), b.real());
|
|
||||||
ASSERT_EQ(a.imag(), b.imag());
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename A, typename B>
|
|
||||||
void COMPLEX_FLOAT_EQ(
|
|
||||||
const std::complex<A>& a,
|
|
||||||
const std::complex<B>& b,
|
|
||||||
const long double epsilon=0
|
|
||||||
) {
|
|
||||||
if (epsilon) {
|
|
||||||
ASSERT_NEAR(a.real(), b.real(), epsilon);
|
|
||||||
ASSERT_NEAR(a.imag(), b.imag(), epsilon);
|
|
||||||
} else {
|
|
||||||
ASSERT_FLOAT_EQ(a.real(), b.real());
|
|
||||||
ASSERT_FLOAT_EQ(a.imag(), b.imag());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename A, typename B>
|
|
||||||
void COMPLEX_EQ_VEC(
|
|
||||||
const std::vector<std::complex<A>>& a,
|
|
||||||
const std::vector<std::complex<A>>& b
|
|
||||||
) {
|
|
||||||
if (a.size() != b.size()) { FAIL(); }
|
|
||||||
for (int i = 0; i < a.size(); ++i) {
|
|
||||||
COMPLEX_EQ(a[i], b[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename A, typename B>
|
|
||||||
void COMPLEX_FLOAT_EQ_VEC(
|
|
||||||
const std::vector<std::complex<A>>& a,
|
|
||||||
const std::vector<std::complex<B>>& b,
|
|
||||||
const long double epsilon
|
|
||||||
) {
|
|
||||||
if (a.size() != b.size()) { FAIL(); }
|
|
||||||
for (int i = 0; i < a.size(); ++i) {
|
|
||||||
COMPLEX_FLOAT_EQ(a[i], b[i], epsilon);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(FFTTest, TestFFT) {
|
|
||||||
std::vector<std::vector<std::complex<double>>> input = {
|
|
||||||
{1.0, 0.5, 0},
|
|
||||||
{1,1,1,1,1,1,1,1},
|
|
||||||
|
|
||||||
};
|
|
||||||
std::vector<std::vector<std::complex<double>>> expected = {
|
|
||||||
{1.5,1.f-0.5if,0.5,1.f+0.5if},
|
|
||||||
{8, 0, 0, 0, 0, 0, 0, 0}
|
|
||||||
};
|
|
||||||
for (int i = 0; i < input.size(); ++i) {
|
|
||||||
COMPLEX_FLOAT_EQ_VEC(
|
|
||||||
nb::fft2(input[i]),
|
|
||||||
expected[i],
|
|
||||||
1e-10
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include <NBCore/Events.hpp>
|
#include "Events.hpp"
|
||||||
|
|
||||||
namespace NB {
|
namespace NB {
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,365 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_BUFFER
|
||||||
|
#define _NB_BUFFER
|
||||||
|
|
||||||
|
#include "GLLoad.hpp"
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include <NBCore/Errors.hpp>
|
||||||
|
#include <NBCore/Types.hpp>
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
typedef std::vector<unsigned char> RawVec;
|
||||||
|
|
||||||
|
static uint8_t GLSLTypeSize(GLenum type) {
|
||||||
|
switch(type) {
|
||||||
|
case GL_SHORT:
|
||||||
|
case GL_UNSIGNED_SHORT:
|
||||||
|
case GL_HALF_FLOAT:
|
||||||
|
return 2;
|
||||||
|
break;
|
||||||
|
case GL_INT:
|
||||||
|
case GL_UNSIGNED_INT:
|
||||||
|
case GL_FLOAT:
|
||||||
|
return 4;
|
||||||
|
break;
|
||||||
|
case GL_DOUBLE:
|
||||||
|
return 8;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VertexAttributePointer {
|
||||||
|
GLuint buffer = 0;
|
||||||
|
int32_t offset = 0;
|
||||||
|
GLsizei stride = -1;
|
||||||
|
GLuint divisor = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct VertexAttribute {
|
||||||
|
GLint GLSLSize;
|
||||||
|
GLenum GLSLType;
|
||||||
|
GLboolean GLSLNormalization;
|
||||||
|
VertexAttributePointer ptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
static bool isIndexInVertexAttribute(int i, const VertexAttribute& va) {
|
||||||
|
if ((i -= va.ptr.offset) < 0) { return false; }
|
||||||
|
return (i%va.ptr.stride) < GLSLTypeSize(va.GLSLType) * va.GLSLSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef std::vector<VertexAttribute> VertexAttributeList;
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
RawVec vectorToRaw(const std::vector<T>& vec) {
|
||||||
|
unsigned int num_bytes = vec.size() * sizeof(T);
|
||||||
|
RawVec ret(num_bytes);
|
||||||
|
memcpy(ret.data(), vec.data(), num_bytes);
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename T, typename S>
|
||||||
|
RawVec concatVectorsToRaw(const std::vector<T>& vec1, const std::vector<S>& vec2) {
|
||||||
|
RawVec vec1_raw = vectorToRaw<T>(vec1);
|
||||||
|
RawVec vec2_raw = vectorToRaw<S>(vec2);
|
||||||
|
unsigned int vec1_raw_size = vec1_raw.size();
|
||||||
|
unsigned int vec2_raw_size = vec2_raw.size();
|
||||||
|
RawVec ret(vec1_raw_size + vec2_raw_size);
|
||||||
|
memcpy(ret.data(), vec1_raw.data(), vec1_raw_size);
|
||||||
|
memcpy(ret.data() + vec1_raw_size, vec2_raw.data(), vec2_raw_size);
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
std::vector<T> rawToVector(const RawVec& vec) {
|
||||||
|
if (vec.size() % sizeof(T) != 0) {
|
||||||
|
throw std::runtime_error("Data size does not align to std::vector<" + std::string(typeid(T).name()) + ">.");
|
||||||
|
}
|
||||||
|
unsigned int num_elmts = vec.size() / sizeof(T);
|
||||||
|
std::vector<T> ret(num_elmts);
|
||||||
|
memcpy(ret.data(), vec.data(), vec.size());
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
class BufferError : public std::runtime_error {
|
||||||
|
public:
|
||||||
|
const bool error;
|
||||||
|
BufferError(const std::string& msg, const std::string& file="", int line=-1)
|
||||||
|
: std::runtime_error(NB::formatDebugString(msg, file, line)), error(true) {}
|
||||||
|
BufferError(bool isError=true) : std::runtime_error(""), error(isError) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
template <typename ObjectType>
|
||||||
|
class OpenGLObject {
|
||||||
|
public:
|
||||||
|
OpenGLObject(OpenGLObject&&) = default;
|
||||||
|
OpenGLObject& operator=(OpenGLObject&&) = default;
|
||||||
|
~OpenGLObject() { remove(); }
|
||||||
|
|
||||||
|
virtual void bind() const = 0;
|
||||||
|
virtual void unbind() const = 0;
|
||||||
|
virtual bool isInitialized() const = 0;
|
||||||
|
GLuint id() const { return _id; }
|
||||||
|
|
||||||
|
protected:
|
||||||
|
OpenGLObject() = default;
|
||||||
|
OpenGLObject(const OpenGLObject&) = delete;
|
||||||
|
OpenGLObject& operator=(const OpenGLObject&) = delete;
|
||||||
|
|
||||||
|
virtual void remove() const = 0;
|
||||||
|
|
||||||
|
GLuint _id;
|
||||||
|
};
|
||||||
|
|
||||||
|
class VAO : public virtual OpenGLObject<VAO> {
|
||||||
|
public:
|
||||||
|
using Base = OpenGLObject<VAO>;
|
||||||
|
using Base::Base;
|
||||||
|
|
||||||
|
VAO() { glGenVertexArrays(1, &_id); }
|
||||||
|
|
||||||
|
void bind() const { glBindVertexArray(_id); }
|
||||||
|
void unbind() const { glBindVertexArray(0); }
|
||||||
|
|
||||||
|
|
||||||
|
protected:
|
||||||
|
using Base::_id;
|
||||||
|
const
|
||||||
|
|
||||||
|
void remove() { glDeleteVertexArrays(1, &_id); }
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename BufferType>
|
||||||
|
class Buffer : public virtual OpenGLObject<Buffer<BufferType>> {
|
||||||
|
public:
|
||||||
|
using Base = OpenGLObject<Buffer>;
|
||||||
|
using Base::Base;
|
||||||
|
|
||||||
|
Buffer(GLenum usage_ = GL_STATIC_DRAW) : usage(usage_) { glGenBuffers(1, &_id); }
|
||||||
|
|
||||||
|
void bind() const { glBindBuffer(GLTarget, _id); }
|
||||||
|
void unbind() const { glBindBuffer(GLTarget, 0); }
|
||||||
|
void data(void* data_, size_t size) const { glBufferData(GLTarget, size, data_, usage); }
|
||||||
|
void data(nb::ByteVector& data_) const { glBufferData(GLTarget, data_.size(), data_.data(), usage); }
|
||||||
|
void invalidate() const { glInvalidateBufferData(_id); }
|
||||||
|
|
||||||
|
|
||||||
|
const GLenum GLTarget = BufferType::GLTarget;
|
||||||
|
GLenum usage;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
using Base::_id;
|
||||||
|
void remove() { glDeleteBuffers(1, &_id); }
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
class VertexBuffer : public virtual Buffer<VertexBuffer> {
|
||||||
|
public:
|
||||||
|
|
||||||
|
static const GLenum GLTarget = GL_ARRAY_BUFFER;
|
||||||
|
protected:
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
class ElementBuffer : public virtual Buffer<ElementBuffer> {
|
||||||
|
public:
|
||||||
|
|
||||||
|
static const GLenum GLTarget = GL_ELEMENT_ARRAY_BUFFER;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
class Buffer : public OpenGLObject {
|
||||||
|
public:
|
||||||
|
Buffer(
|
||||||
|
GLenum buffer_type,
|
||||||
|
GLenum usage=GL_STATIC_DRAW
|
||||||
|
) : _type(buffer_type), _usage(usage) {
|
||||||
|
glGenBuffers(1, &_id);
|
||||||
|
}
|
||||||
|
Buffer(
|
||||||
|
const RawVec& init_data,
|
||||||
|
GLenum buffer_type,
|
||||||
|
GLenum usage=GL_STATIC_DRAW
|
||||||
|
) : _type{buffer_type}, _usage{usage} { data(init_data); }
|
||||||
|
Buffer(
|
||||||
|
unsigned int size,
|
||||||
|
GLenum buffer_type,
|
||||||
|
GLenum usage=GL_STATIC_DRAW
|
||||||
|
) : Buffer(RawVec(size), buffer_type, usage) {}
|
||||||
|
|
||||||
|
Buffer(Buffer&& rhs) { *this = std::move(rhs); }
|
||||||
|
Buffer& operator=(Buffer&& rhs) {
|
||||||
|
remove();
|
||||||
|
_usage = rhs._usage;
|
||||||
|
_id = rhs._id;
|
||||||
|
rhs._id = 0;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
GLenum usage() const { return _usage; }
|
||||||
|
unsigned int id() const { return _id; }
|
||||||
|
GLuint size() const { return _size; }
|
||||||
|
bool isInitialized() const override { return _id && glIsBuffer(_id) && bool(_size); }
|
||||||
|
RawVec data() const {
|
||||||
|
RawVec ret(_size);
|
||||||
|
bind();
|
||||||
|
glGetBufferSubData(_type, 0, _size, ret.data());
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
void bind() const override { glBindBuffer(_type, _id); }
|
||||||
|
void unbind() const override { glBindBuffer(_type, 0); }
|
||||||
|
|
||||||
|
GLenum usage(GLenum usage) {
|
||||||
|
_usage=usage;
|
||||||
|
data(data());
|
||||||
|
return _usage;
|
||||||
|
}
|
||||||
|
void data(const RawVec& set_data) {
|
||||||
|
if (!glfwGetCurrentContext()) {
|
||||||
|
THROW_BUFFER_ERROR("No OpenGL context.");
|
||||||
|
}
|
||||||
|
bind();
|
||||||
|
glBufferData(_type, set_data.size(), set_data.data(), _usage);
|
||||||
|
_size = set_data.size();
|
||||||
|
}
|
||||||
|
void data(const RawVec& newData, unsigned int offset) {
|
||||||
|
if (newData.size()+offset > _size) {
|
||||||
|
THROW_BUFFER_ERROR("Attempting to overflow buffer of capacity " + std::to_string(_size) + ".");
|
||||||
|
}
|
||||||
|
bind();
|
||||||
|
glBufferSubData(_type, offset, newData.size(), newData.data());
|
||||||
|
}
|
||||||
|
void data(void* src, unsigned int offset, unsigned int size) {
|
||||||
|
if (size+offset > _size) {
|
||||||
|
THROW_BUFFER_ERROR("Attempting to overflow buffer of capacity " + std::to_string(_size) + ".");
|
||||||
|
}
|
||||||
|
bind();
|
||||||
|
glBufferSubData(_type, offset, size, src);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected:
|
||||||
|
virtual void remove() const override {
|
||||||
|
unbind();
|
||||||
|
if (_id) { glDeleteBuffers(1, &_id); }
|
||||||
|
}
|
||||||
|
|
||||||
|
using OpenGLObject::_id;
|
||||||
|
GLenum _type;
|
||||||
|
GLenum _usage;
|
||||||
|
unsigned int _size = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
class Texture : public OpenGLObject {
|
||||||
|
public:
|
||||||
|
Texture(GLenum tar=GL_TEXTURE_2D) : _target(tar) { glGenTextures(1, &_id); }
|
||||||
|
|
||||||
|
Texture(Texture&& rhs) { *this=std::move(rhs); }
|
||||||
|
Texture& operator=(Texture&& rhs) {
|
||||||
|
_target = rhs._target;
|
||||||
|
_id = rhs._id;
|
||||||
|
rhs._id = 0;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void bind() const override { glBindTexture(_target, _id); }
|
||||||
|
void unbind() const override { glBindTexture(_target, 0); }
|
||||||
|
bool isInitialized() const override { return _id && glIsTexture(_id); }
|
||||||
|
|
||||||
|
protected:
|
||||||
|
using OpenGLObject::_id;
|
||||||
|
GLenum _target;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Framebuffer : public OpenGLObject {
|
||||||
|
public:
|
||||||
|
|
||||||
|
Framebuffer(GLenum tar=GL_FRAMEBUFFER) : _target(tar) { glGenFramebuffers(1, &_id); }
|
||||||
|
|
||||||
|
Framebuffer(Framebuffer&& rhs) { *this=std::move(rhs); }
|
||||||
|
Framebuffer& operator=(Framebuffer&& rhs) {
|
||||||
|
remove();
|
||||||
|
_target = rhs._target;
|
||||||
|
_id = rhs._id;
|
||||||
|
rhs._id = 0;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void bind() const override { glBindFramebuffer(_target, _id); }
|
||||||
|
void unbind() const override { glBindFramebuffer(_target, 0); }
|
||||||
|
bool isInitialized() const override { return _id && glIsFramebuffer(_id); }
|
||||||
|
GLenum status() const {
|
||||||
|
bind();
|
||||||
|
return glCheckFramebufferStatus(_target);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected:
|
||||||
|
virtual void remove() const override {
|
||||||
|
unbind();
|
||||||
|
if (_id) { glDeleteFramebuffers(1, &_id); }
|
||||||
|
}
|
||||||
|
using OpenGLObject::_id;
|
||||||
|
GLenum _target;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Renderbuffer : public OpenGLObject {
|
||||||
|
public:
|
||||||
|
Renderbuffer(unsigned int x, unsigned int y, GLenum format=GL_RGBA32F, unsigned int multi=0) : Renderbuffer() {
|
||||||
|
storage(x, y, format, multi);
|
||||||
|
}
|
||||||
|
Renderbuffer() { glGenRenderbuffers(1, &_id); }
|
||||||
|
|
||||||
|
|
||||||
|
Renderbuffer(Renderbuffer&& rhs) { *this = std::move(rhs); }
|
||||||
|
Renderbuffer& operator=(Renderbuffer&& rhs) {
|
||||||
|
_format = rhs._format;
|
||||||
|
_id = rhs._id;
|
||||||
|
rhs._id = 0;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
virtual void bind() const override { glBindRenderbuffer(GL_RENDERBUFFER, _id); }
|
||||||
|
virtual void unbind() const override { glBindRenderbuffer(GL_RENDERBUFFER, _id); }
|
||||||
|
virtual bool isInitialized() const override { return _id && glIsRenderbuffer(_id); }
|
||||||
|
|
||||||
|
void storage(unsigned int x, unsigned int y, GLenum format=GL_RGBA32F, unsigned int multi=0) {
|
||||||
|
_sizex = x;
|
||||||
|
_sizey = y;
|
||||||
|
_format = format;
|
||||||
|
_multisample = multi;
|
||||||
|
bind();
|
||||||
|
glRenderbufferStorageMultisample(GL_RENDERBUFFER, _multisample, _format, _sizex, _sizey);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected:
|
||||||
|
virtual void remove() const override {
|
||||||
|
unbind();
|
||||||
|
if (_id) { glDeleteRenderbuffers(1, &_id); }
|
||||||
|
}
|
||||||
|
|
||||||
|
using OpenGLObject::_id;
|
||||||
|
GLenum _format;
|
||||||
|
unsigned int _sizex{0};
|
||||||
|
unsigned int _sizey{0};
|
||||||
|
unsigned int _multisample{0};
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
} // namespace NB
|
||||||
|
#endif // _NB_BUFFER
|
||||||
@@ -1,56 +1,27 @@
|
|||||||
cmake_minimum_required(VERSION 3.10)
|
include_directories(./.)
|
||||||
project(NBGraphics VERSION 0.1)
|
|
||||||
|
|
||||||
include(GNUInstallDirs)
|
find_package(OpenGL)
|
||||||
include(CMakePackageConfigHelpers)
|
add_subdirectory(${GLFW_PATH} ${GLFW_PATH}/build)
|
||||||
|
|
||||||
set(GLAD_PATH ${NBENGINE_ROOT}/../glad/)
|
include_directories(${GLFW_PATH}/include ${GLAD_PATH}/include)
|
||||||
get_filename_component(GLAD_PATH ${GLAD_PATH} ABSOLUTE)
|
|
||||||
|
|
||||||
set(CMAKE_PREFIX_PATH
|
|
||||||
"${CMAKE_PREFIX_PATH}"
|
|
||||||
"C:/Program Files (x86)/GLFW/lib/cmake/glfw3/"
|
|
||||||
)
|
|
||||||
find_package(OpenGL REQUIRED)
|
|
||||||
find_package(glfw3 REQUIRED)
|
|
||||||
|
|
||||||
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
|
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
|
||||||
if (NB_BUILD_TESTS)
|
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||||
set(GLFW_BUILD_TESTS ON CACHE BOOL "" FORCE)
|
|
||||||
else()
|
|
||||||
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
|
||||||
endif()
|
|
||||||
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||||
|
|
||||||
if (NB_MONITOR_OPENGL_CALLS)
|
|
||||||
add_compile_definitions(_NB_MONITOR_OPENGL_CALLS)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
toAbsolutePath(NB_GRAPHICS_SOURCE
|
toAbsolutePath(NB_GRAPHICS_SOURCE
|
||||||
./src/Buffers.cpp
|
|
||||||
./src/FrameBuffers.cpp
|
|
||||||
./src/Image.cpp
|
|
||||||
./src/Mesh.cpp
|
|
||||||
./src/OGLObjects.cpp
|
|
||||||
./src/ProgramPipeline.cpp
|
|
||||||
./src/Textures.cpp
|
|
||||||
./src/VertexArray.cpp
|
|
||||||
./src/VertexData.cpp
|
|
||||||
./src/Window.cpp
|
./src/Window.cpp
|
||||||
|
./src/Buffers.cpp
|
||||||
)
|
)
|
||||||
|
|
||||||
toAbsolutePath(NB_GRAPHICS_INCLUDE
|
toAbsolutePath(NB_GRAPHICS_INCLUDE
|
||||||
./include/NBGraphics/Buffers.hpp
|
./Buffers.hpp
|
||||||
./include/NBGraphics/Camera.hpp
|
./Camera.hpp
|
||||||
./include/NBGraphics/FrameBuffers.hpp
|
./Draw.hpp
|
||||||
./include/NBGraphics/GLLoad.hpp
|
./GLLoad.hpp
|
||||||
./include/NBGraphics/Image.hpp
|
./shader.hpp
|
||||||
./include/NBGraphics/Mesh.hpp
|
./VAOManager.hpp
|
||||||
./include/NBGraphics/OGLObjects.hpp
|
./Window.hpp
|
||||||
./include/NBGraphics/ProgramPipeline.hpp
|
|
||||||
./include/NBGraphics/Textures.hpp
|
|
||||||
./include/NBGraphics/VertexArray.hpp
|
|
||||||
./include/NBGraphics/VertexData.hpp
|
|
||||||
./include/NBGraphics/Window.hpp
|
|
||||||
)
|
)
|
||||||
|
|
||||||
set(NB_GRAPHICS_SOURCE ${NB_GRAPHICS_SOURCE} PARENT_SCOPE)
|
set(NB_GRAPHICS_SOURCE ${NB_GRAPHICS_SOURCE} PARENT_SCOPE)
|
||||||
@@ -60,62 +31,4 @@ add_library(NBGraphics
|
|||||||
${NB_GRAPHICS_SOURCE}
|
${NB_GRAPHICS_SOURCE}
|
||||||
${GLAD_PATH}/src/glad.c
|
${GLAD_PATH}/src/glad.c
|
||||||
)
|
)
|
||||||
add_library(NBEngine::Graphics ALIAS NBGraphics)
|
target_link_libraries(NBGraphics glfw3)
|
||||||
add_dependencies(NBGraphics NBCore)
|
|
||||||
add_dependencies(NBGraphics glfw)
|
|
||||||
target_link_libraries(NBGraphics
|
|
||||||
PUBLIC glfw
|
|
||||||
PUBLIC NBCore
|
|
||||||
)
|
|
||||||
target_include_directories(NBGraphics
|
|
||||||
PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
|
|
||||||
PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
|
|
||||||
PUBLIC "${GLAD_PATH}/include"
|
|
||||||
)
|
|
||||||
export(
|
|
||||||
TARGETS NBGraphics
|
|
||||||
FILE "${CMAKE_BINARY_DIR}/cmake/NBGraphicsTargets.cmake"
|
|
||||||
NAMESPACE NBEngine::
|
|
||||||
)
|
|
||||||
configure_package_config_file(
|
|
||||||
"NBGraphicsConfig.cmake.in"
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfig.cmake"
|
|
||||||
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
|
|
||||||
PATH_VARS CMAKE_INSTALL_LIBDIR
|
|
||||||
)
|
|
||||||
write_basic_package_version_file(
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfigVersion.cmake"
|
|
||||||
COMPATIBILITY AnyNewerVersion
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if (NBENGINE_INSTALL)
|
|
||||||
message("Installing NBGraphics to ${CMAKE_INSTALL_PREFIX}")
|
|
||||||
install(
|
|
||||||
TARGETS NBGraphics
|
|
||||||
EXPORT NBGraphicsTargets
|
|
||||||
LIBRARY DESTINATION lib
|
|
||||||
ARCHIVE DESTINATION lib
|
|
||||||
INCLUDES DESTINATION include
|
|
||||||
)
|
|
||||||
install(
|
|
||||||
DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/NBGraphics"
|
|
||||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
|
|
||||||
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
|
|
||||||
)
|
|
||||||
install(
|
|
||||||
EXPORT NBGraphicsTargets
|
|
||||||
DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
|
|
||||||
NAMESPACE NBEngine::
|
|
||||||
)
|
|
||||||
install(FILES
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfig.cmake"
|
|
||||||
"${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfigVersion.cmake"
|
|
||||||
DESTINATION "${CMAKE_INSTALL_PREFIX}/CMake"
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
if (NB_BUILD_TESTS)
|
|
||||||
add_subdirectory(./tests)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,14 +2,13 @@
|
|||||||
#ifndef _NB_CAMERA
|
#ifndef _NB_CAMERA
|
||||||
#define _NB_CAMERA
|
#define _NB_CAMERA
|
||||||
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
#include <GLLoad.h>
|
||||||
|
|
||||||
#include <glm/glm.hpp>
|
#include <glm/glm.hpp>
|
||||||
#include <glm/gtc/matrix_inverse.hpp>
|
#include <glm/gtc/matrix_inverse.hpp>
|
||||||
#include <glm/gtc/matrix_transform.hpp>
|
#include <glm/gtc/matrix_transform.hpp>
|
||||||
#include <glm/gtc/type_ptr.hpp>
|
#include <glm/gtc/type_ptr.hpp>
|
||||||
|
|
||||||
namespace nb {
|
namespace NB {
|
||||||
|
|
||||||
class Camera {
|
class Camera {
|
||||||
public:
|
public:
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_DRAW
|
||||||
|
#define _NB_DRAW
|
||||||
|
|
||||||
|
#include <GLLoad.h>
|
||||||
|
|
||||||
|
#include <exception>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "Buffers.h"
|
||||||
|
#include "Shader.h"
|
||||||
|
#include "VAOManager.hpp"
|
||||||
|
|
||||||
|
#define THROW_DRAW_ERROR(msg) throw DrawError(msg, __FILE__, __LINE__);
|
||||||
|
|
||||||
|
namespace NB{
|
||||||
|
|
||||||
|
class DrawError : public std::runtime_error {
|
||||||
|
public:
|
||||||
|
DrawError(const std::string&, const std::string& file="", int line=-1);
|
||||||
|
};
|
||||||
|
|
||||||
|
uint8_t VerticesFromPrimitives(GLenum, unsigned int num_prims=1);
|
||||||
|
|
||||||
|
uint8_t PrimitivesFromVertices(GLenum, unsigned int);
|
||||||
|
|
||||||
|
void copyVertexAttribute(const VertexAttribute&, VertexAttribute&);
|
||||||
|
|
||||||
|
class DrawBuffer {
|
||||||
|
public:
|
||||||
|
typedef std::shared_ptr<Buffer> BufferManagerPointer;
|
||||||
|
DrawBuffer(VertexAttributeList, GLenum prim_type=GL_TRIANGLES);
|
||||||
|
//DrawBuffer(std::initializer_list<VertexAttribute>, std::initializer_list<VertexAttributePointer>);
|
||||||
|
|
||||||
|
unsigned int vertSize() const;
|
||||||
|
const std::shared_ptr<ShaderProgram> shader() const;
|
||||||
|
unsigned int elementBufferID() const;
|
||||||
|
unsigned int vertexBufferID() const;
|
||||||
|
virtual void draw() const;
|
||||||
|
RawVec vertAttrData(unsigned int);
|
||||||
|
|
||||||
|
VertexAttributeList changeVertLayout(unsigned int, VertexAttributePointer);
|
||||||
|
RawVec vertAttrData(unsigned int, const RawVec&);
|
||||||
|
virtual void elementData(const std::vector<unsigned int>&);
|
||||||
|
virtual void elementData(unsigned int);
|
||||||
|
virtual void elementData(const std::vector<unsigned int>&, unsigned int offset);
|
||||||
|
virtual void vertexData(const RawVec&);
|
||||||
|
virtual void vertexData(unsigned int num_verts);
|
||||||
|
virtual void vertexData(const RawVec&, unsigned int offset);
|
||||||
|
|
||||||
|
BufferManagerPointer _vert_data;
|
||||||
|
BufferManagerPointer _elmt_data;
|
||||||
|
VAOManager _VAO;
|
||||||
|
const GLenum _gl_primitive_type=0;
|
||||||
|
virtual VertexAttributeList defaultVAO(VertexAttributeList);
|
||||||
|
|
||||||
|
unsigned int _num_verts, _num_prims;
|
||||||
|
protected:
|
||||||
|
};
|
||||||
|
|
||||||
|
class DrawInstanceBuffer : public DrawBuffer {
|
||||||
|
public:
|
||||||
|
DrawInstanceBuffer(VertexAttributeList, VertexAttributeList, GLenum primt_type=GL_TRIANGLES);
|
||||||
|
|
||||||
|
unsigned int instSize() const;
|
||||||
|
unsigned int instanceBufferID() const;
|
||||||
|
virtual void draw() const override;
|
||||||
|
|
||||||
|
VertexAttributeList changeInstanceLayout(unsigned int, VertexAttributePointer);
|
||||||
|
virtual void instanceData(const RawVec&);
|
||||||
|
virtual void instanceData(unsigned int);
|
||||||
|
virtual void instanceData(const RawVec&, unsigned int offset);
|
||||||
|
|
||||||
|
BufferManagerPointer _inst_data;
|
||||||
|
virtual VertexAttributeList defaultVAO(VertexAttributeList);
|
||||||
|
unsigned int _num_inst;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_OPENGL_LOADER
|
||||||
|
#define _NB_OPENGL_LOADER
|
||||||
|
|
||||||
|
#include <glad/glad.h>
|
||||||
|
#include <GLFW/glfw3.h>
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace NB {
|
||||||
|
|
||||||
|
static unsigned int __NB_GL_DEBUG_ERROR_CODE__;
|
||||||
|
|
||||||
|
static std::string formatDebugString(const std::string& msg, const std::string& file="", int line=-1) {
|
||||||
|
std::string ret = "";
|
||||||
|
if (file != "") {
|
||||||
|
ret += "In file " + file;
|
||||||
|
if (line >= 0) {
|
||||||
|
ret += " at line " + std::to_string(line);
|
||||||
|
}
|
||||||
|
ret += ":\n\t";
|
||||||
|
}
|
||||||
|
return ret + msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
#define NB_GL_DEBUG_THROW(cmd, when) while(NB::__NB_GL_DEBUG_ERROR_CODE__=glGetError()){\
|
||||||
|
std::cout << "[GL ERROR]: " << NB::__NB_GL_DEBUG_ERROR_CODE__;\
|
||||||
|
std::cout << " " << when << " " << cmd << "\n";\
|
||||||
|
}
|
||||||
|
#define NB_GL_DEBUG(cmd) NB_GL_DEBUG_THROW(#cmd, "before"); cmd; NB_GL_DEBUG_THROW(#cmd, "after");
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
@PACKAGE_INIT@
|
|
||||||
include("${CMAKE_CURRENT_LIST_DIR}/NBGraphicsTargets.cmake")
|
|
||||||
include(CMakeFindDependencyMacro)
|
|
||||||
find_dependency(NBCore REQUIRED)
|
|
||||||
find_dependency(OpenGL REQUIRED)
|
|
||||||
find_dependency(glfw3 REQUIRED)
|
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_VAO_MANAGER
|
||||||
|
#define _NB_VAO_MANAGER
|
||||||
|
|
||||||
|
#include <GLLoad.h>
|
||||||
|
|
||||||
|
#include <exception>
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "Buffers.h"
|
||||||
|
|
||||||
|
#define THROW_VAO_ERROR(msg) throw VAOError(msg, __FILE__, __LINE__);
|
||||||
|
|
||||||
|
namespace NB {
|
||||||
|
|
||||||
|
class VAOError : public std::runtime_error {
|
||||||
|
public:
|
||||||
|
const bool error;
|
||||||
|
VAOError(const std::string& msg, const std::string& file="", int line=-1)
|
||||||
|
: std::runtime_error(NB::formatDebugString(msg, file, line)), error(true) {}
|
||||||
|
VAOError(bool isError=true) : std::runtime_error(""), error(isError) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
class VAOManager : public OpenGLObject {
|
||||||
|
public:
|
||||||
|
typedef std::shared_ptr<Buffer> BufferManagerPointer;
|
||||||
|
//typedef BufferManager BufferManagerPointer;
|
||||||
|
|
||||||
|
VAOManager();
|
||||||
|
VAOManager(
|
||||||
|
std::vector<BufferManagerPointer>,
|
||||||
|
BufferManagerPointer elmt_buf = nullptr,
|
||||||
|
const VertexAttributeList& vert_attrs = {}
|
||||||
|
);
|
||||||
|
VAOManager(
|
||||||
|
BufferManagerPointer vert_bufs,
|
||||||
|
BufferManagerPointer elmt_buf = nullptr,
|
||||||
|
const VertexAttributeList& vert_attrs = {}
|
||||||
|
) : VAOManager(std::vector<BufferManagerPointer>(1, vert_bufs), elmt_buf, vert_attrs) {}
|
||||||
|
|
||||||
|
VAOManager(VAOManager&& rhs);
|
||||||
|
VAOManager& operator=(VAOManager&& rhs);
|
||||||
|
|
||||||
|
VertexAttributeList getLayout() const;
|
||||||
|
GLuint id() const;
|
||||||
|
unsigned int vertSize(GLuint) const;
|
||||||
|
std::vector<BufferManagerPointer> getVertexBuffers() const;
|
||||||
|
bool isInitialized() const override;
|
||||||
|
RawVec attributeData(unsigned int);
|
||||||
|
|
||||||
|
RawVec attributeData(unsigned int, const RawVec&);
|
||||||
|
void bind() const;
|
||||||
|
void unbind() const;
|
||||||
|
void addVBO(BufferManagerPointer);
|
||||||
|
void changeEBO(BufferManagerPointer);
|
||||||
|
VertexAttributeList addVertexAttributes(const VertexAttributeList&);
|
||||||
|
VertexAttributeList addVertexAttributes(VertexAttribute);
|
||||||
|
VertexAttributeList generate();
|
||||||
|
VertexAttributeList generate(VertexAttributeList);
|
||||||
|
VertexAttributeList changeLayout(unsigned int, VertexAttributePointer);
|
||||||
|
|
||||||
|
VAOError checkValid(const VertexAttributeList&);
|
||||||
|
|
||||||
|
private:
|
||||||
|
void remove() const override;
|
||||||
|
|
||||||
|
using OpenGLObject::_id;
|
||||||
|
std::map<GLuint, BufferManagerPointer> _vert_buffers;
|
||||||
|
BufferManagerPointer _elmt_buffer = nullptr;
|
||||||
|
VertexAttributeList _vert_attrs;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace NB
|
||||||
|
#endif // _NB_VAO_MANAGER
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_WINDOW
|
||||||
|
#define _NB_WINDOW
|
||||||
|
|
||||||
|
#include "GLLoad.hpp"
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <array>
|
||||||
|
#include <map>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace nb {
|
||||||
|
|
||||||
|
class GLError : public std::runtime_error {
|
||||||
|
public:
|
||||||
|
GLError(const std::string&);
|
||||||
|
};
|
||||||
|
|
||||||
|
class WindowError : public std::runtime_error {
|
||||||
|
public:
|
||||||
|
WindowError(const std::string&);
|
||||||
|
};
|
||||||
|
|
||||||
|
class Window {
|
||||||
|
public:
|
||||||
|
static bool StrictInitialization;
|
||||||
|
|
||||||
|
static int getGLFWHint(int);
|
||||||
|
static int setGLFWHint(int, int);
|
||||||
|
static Window* getCurrent();
|
||||||
|
|
||||||
|
Window(const std::array<uint16_t, 2>, const char*, GLFWmonitor* initMonitor=NULL, GLFWwindow* initWindow=NULL);
|
||||||
|
Window(const uint16_t, const uint16_t, const char*, GLFWmonitor* initMonitor=NULL, GLFWwindow* initWindow=NULL);
|
||||||
|
~Window();
|
||||||
|
|
||||||
|
int getWindowHint(int) const;
|
||||||
|
GLFWwindow* getWindow() const;
|
||||||
|
std::array<uint16_t, 2> getSize() const;
|
||||||
|
float getAspectRatio() const;
|
||||||
|
std::string getName() const;
|
||||||
|
|
||||||
|
int init();
|
||||||
|
int setWindowHint(int, int);
|
||||||
|
void setCurrent();
|
||||||
|
void resize(const std::array<uint16_t, 2>);
|
||||||
|
void resize(const uint16_t x, const uint16_t y);
|
||||||
|
|
||||||
|
protected:
|
||||||
|
static std::map<GLFWwindow*, Window*> WindowContexts;
|
||||||
|
static std::map<int, int> GLFWHints;
|
||||||
|
static Window* _current;
|
||||||
|
static bool _glfw_init;
|
||||||
|
static bool checkKillGLFW();
|
||||||
|
|
||||||
|
std::map<int, int> windowHints;
|
||||||
|
std::array<uint16_t, 2> windowSize;
|
||||||
|
float _aspect_ratio;
|
||||||
|
std::string windowName;
|
||||||
|
GLFWwindow* window;
|
||||||
|
GLFWmonitor* monitor;
|
||||||
|
GLFWwindow* shareWindow;
|
||||||
|
bool _init = false;
|
||||||
|
int gladResponse = -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
};
|
||||||
|
#endif
|
||||||
@@ -1,262 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_BUFFER
|
|
||||||
#define _NB_BUFFER
|
|
||||||
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
#include <NBCore/Logger.hpp>
|
|
||||||
#include <NBCore/Utils.hpp>
|
|
||||||
|
|
||||||
#include <NBGraphics/OGLObjects.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
extern const ConstantMap <GLenum, std::string> BufferTypes;
|
|
||||||
|
|
||||||
template<GLenum N>
|
|
||||||
struct GLSLEnum;
|
|
||||||
template<typename T>
|
|
||||||
struct GLSLType;
|
|
||||||
|
|
||||||
#define GLSLTypeTraits(type_, size_, value_) \
|
|
||||||
template<>\
|
|
||||||
struct GLSLEnum<value_> {\
|
|
||||||
using type = type_;\
|
|
||||||
static constexpr size_t size = size_;\
|
|
||||||
static constexpr GLenum value=value_;\
|
|
||||||
};\
|
|
||||||
template<>\
|
|
||||||
struct GLSLType<type_> {\
|
|
||||||
using type = type_;\
|
|
||||||
static constexpr size_t size = size_;\
|
|
||||||
static constexpr GLenum value=value_;\
|
|
||||||
};
|
|
||||||
|
|
||||||
#define GLSLTypeEquivalence(original, newtype) \
|
|
||||||
template<>\
|
|
||||||
struct GLSLType<newtype> : public GLSLType<original> {};
|
|
||||||
|
|
||||||
GLSLTypeTraits(uint8_t, 1, GL_UNSIGNED_BYTE);
|
|
||||||
GLSLTypeTraits(uint16_t, 2, GL_UNSIGNED_SHORT);
|
|
||||||
GLSLTypeTraits(uint32_t, 4, GL_UNSIGNED_INT);
|
|
||||||
GLSLTypeTraits(int8_t, 1, GL_BYTE);
|
|
||||||
GLSLTypeTraits(int16_t, 2, GL_SHORT);
|
|
||||||
GLSLTypeTraits(int32_t, 4, GL_INT);
|
|
||||||
GLSLTypeTraits(float, 4, GL_FLOAT);
|
|
||||||
GLSLTypeTraits(double, 8, GL_DOUBLE);
|
|
||||||
|
|
||||||
class BufferError : public Error<BufferError> {
|
|
||||||
protected:
|
|
||||||
using Base = Error<BufferError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED,
|
|
||||||
DATA_OVERFLOW,
|
|
||||||
DATA_ERROR,
|
|
||||||
BAD_DATA_TYPE
|
|
||||||
};
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
class Buffer : public OpenGLObject {
|
|
||||||
protected:
|
|
||||||
using Codes = BufferError::Codes;
|
|
||||||
using OpenGLObject::_id;
|
|
||||||
GLenum _usage = GL_STATIC_DRAW;
|
|
||||||
size_t _size;
|
|
||||||
virtual GLuint declare() override {
|
|
||||||
if (!_id) {
|
|
||||||
OPENGL_CALL(glGenBuffers(1, &_id));
|
|
||||||
}
|
|
||||||
this->bind();
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
virtual void remove() override {
|
|
||||||
if (_id) {
|
|
||||||
this->unbind();
|
|
||||||
OPENGL_CALL(glDeleteBuffers(1, &_id));
|
|
||||||
_id = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
const GLenum Target;
|
|
||||||
using OpenGLObject::OpenGLObject;
|
|
||||||
Buffer(GLenum target);
|
|
||||||
Buffer(GLenum target, const ByteVector&, GLenum usage=GL_STATIC_DRAW);
|
|
||||||
Buffer(Buffer&& other);
|
|
||||||
Buffer& operator=(Buffer&& rhs);
|
|
||||||
|
|
||||||
virtual void bind() const override {
|
|
||||||
if (_id) {
|
|
||||||
OPENGL_CALL(glBindBuffer(Target, _id));
|
|
||||||
} else {
|
|
||||||
THROW(OpenGLObjectError(
|
|
||||||
OpenGLObjectError::Codes::INVALID_OBJECT,
|
|
||||||
"w/ BufferType " + BufferTypes[Target]
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
virtual void unbind() const override {
|
|
||||||
OPENGL_CALL(glBindBuffer(Target, 0));
|
|
||||||
}
|
|
||||||
GLenum usage() const;
|
|
||||||
size_t size() const;
|
|
||||||
ByteVector data() const;
|
|
||||||
|
|
||||||
void data(const ByteVector& data, GLenum usage=GL_STATIC_DRAW);
|
|
||||||
void data(const void* data, size_t size, GLenum usage=GL_STATIC_DRAW);
|
|
||||||
void subdata(const void* data, size_t size, GLintptr offset=0);
|
|
||||||
void subdata(const ByteVector& data_, GLintptr offset=0);
|
|
||||||
// virtual void clear() const { glClearBufferData(Target, ) }
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
/* template <typename BufferType>
|
|
||||||
class ImmutableBuffer : public virtual Buffer {
|
|
||||||
public:
|
|
||||||
ImmutableBuffer() = default;
|
|
||||||
ImmutableBuffer(
|
|
||||||
size_t size_,
|
|
||||||
GLenum usage_ = GL_STATIC_DRAW,
|
|
||||||
GLbitfield flags_=0x0
|
|
||||||
) : size(size_), Base::usage(usage_) {
|
|
||||||
glBufferStorage(Target, size, nullptr, flags_);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::weak_ptr<void> map(GLbitfield access_) {
|
|
||||||
if (_map && _mapAccess != access_) { unmap(); }
|
|
||||||
_mapAccess = access_;
|
|
||||||
if (!_map) {
|
|
||||||
bind();
|
|
||||||
glMapBuffer(Target, _mapAccess);
|
|
||||||
}
|
|
||||||
return _map;
|
|
||||||
}
|
|
||||||
void unmap() {
|
|
||||||
bind();
|
|
||||||
glUnmapBuffer(Target);
|
|
||||||
_map.reset();
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t size;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
std::shared_ptr<void> _map = nullptr;
|
|
||||||
GLbitfield _mapAccess = 0;
|
|
||||||
|
|
||||||
}; */
|
|
||||||
|
|
||||||
class UniformBuffer : public Buffer {
|
|
||||||
protected:
|
|
||||||
GLuint _index;
|
|
||||||
|
|
||||||
public:
|
|
||||||
UniformBuffer();
|
|
||||||
void bind() const override;
|
|
||||||
GLuint bufferIndex() const;
|
|
||||||
GLuint bufferIndex(GLuint);
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct IsValidGLElementIndexType {
|
|
||||||
static constexpr bool value = false;
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct ValidGLElementIndexType {
|
|
||||||
static constexpr bool value = true;
|
|
||||||
static constexpr GLenum glsltype = GLSLType<T>::value;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct IsValidGLElementIndexType<uint8_t> : public ValidGLElementIndexType<uint8_t> {};
|
|
||||||
template<>
|
|
||||||
struct IsValidGLElementIndexType<uint16_t> : public ValidGLElementIndexType<uint16_t> {};
|
|
||||||
template<>
|
|
||||||
struct IsValidGLElementIndexType<uint32_t> : public ValidGLElementIndexType<uint32_t> {};
|
|
||||||
|
|
||||||
class ElementBuffer : Buffer {
|
|
||||||
private:
|
|
||||||
template<typename T>
|
|
||||||
inline void checkForElementDataType() {
|
|
||||||
static_assert(IsValidGLElementIndexType<T>::value,
|
|
||||||
"ElementBuffer data type must resolve to one of GL_UNSIGNED_BYTE,"
|
|
||||||
"GL_UNSIGNED_SHORT, or GL_UNSIGNED_INT"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Codes = BufferError::Codes;
|
|
||||||
using OpenGLObject::_id;
|
|
||||||
using Buffer::_usage;
|
|
||||||
using Buffer::_size;
|
|
||||||
using Buffer::declare;
|
|
||||||
using Buffer::remove;
|
|
||||||
GLenum _datatype;
|
|
||||||
template<typename T>
|
|
||||||
inline void checkDatatypeConsistency() {
|
|
||||||
if (_datatype != ValidGLElementIndexType<T>::value) {
|
|
||||||
THROW(BufferError(
|
|
||||||
Codes::BAD_DATA_TYPE,
|
|
||||||
GLenumTable[ValidGLElementIndexType<T>::value] + " not same as buffer "
|
|
||||||
"data type "+GLenumTable[_datatype]
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Buffer::Target;
|
|
||||||
using Buffer::OpenGLObject;
|
|
||||||
using Buffer::bind;
|
|
||||||
using Buffer::unbind;
|
|
||||||
using Buffer::usage;
|
|
||||||
using Buffer::size;
|
|
||||||
template<typename T>
|
|
||||||
ElementBuffer(const std::vector<T>& indices, GLenum usage=GL_STATIC_DRAW) : Buffer(GL_ELEMENT_ARRAY_BUFFER) {
|
|
||||||
data(indices, usage);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline GLenum datatype() { return _datatype; }
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
void data(const std::vector<T>& data, GLenum usage=GL_STATIC_DRAW) {
|
|
||||||
checkForElementDataType<T>();
|
|
||||||
_datatype = ValidGLElementIndexType<T>::glsltype;
|
|
||||||
Buffer::data(vectorToBytes(data), usage);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
void data(const T* data, size_t size, GLenum usage=GL_STATIC_DRAW) {
|
|
||||||
checkForElementDataType<T>();
|
|
||||||
_datatype = ValidGLElementIndexType<T>::glsltype;
|
|
||||||
Buffer::data((void*)data, size * sizeof(T), usage);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
void subdata(const T* data, size_t size, GLintptr offset=0) {
|
|
||||||
checkForElementDataType<T>();
|
|
||||||
checkDatatypeConsistency<T>();
|
|
||||||
Buffer::subdata((void*)data, size * sizeof(T), offset);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
void subdata(const std::vector<T>& data_, GLintptr offset=0) {
|
|
||||||
checkForElementDataType<T>();
|
|
||||||
checkDatatypeConsistency<T>();
|
|
||||||
Buffer::subdata(vectorToBytes(data_), offset);
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace NB
|
|
||||||
#endif // _NB_BUFFER
|
|
||||||
@@ -1,228 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_FRAMEBUFFER
|
|
||||||
#define _NB_FRAMEBUFFER
|
|
||||||
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
|
|
||||||
#include <NBGraphics/Image.hpp>
|
|
||||||
#include <NBGraphics/OGLObjects.hpp>
|
|
||||||
#include <NBGraphics/Textures.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
class FrameBufferError : public Error<FrameBufferError> {
|
|
||||||
protected:
|
|
||||||
using Base = Error<FrameBufferError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, INVALID_VALUE
|
|
||||||
};
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
class RenderBuffer : public RenderTarget {
|
|
||||||
protected:
|
|
||||||
GLuint declare() override {
|
|
||||||
if (!_id) {
|
|
||||||
OPENGL_CALL(
|
|
||||||
glGenRenderbuffers(1, &_id)
|
|
||||||
);
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(glRenderbufferStorage(
|
|
||||||
GL_RENDERBUFFER,
|
|
||||||
format,
|
|
||||||
width,
|
|
||||||
height
|
|
||||||
));
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
bind();
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
void remove() override {
|
|
||||||
if (_id) {
|
|
||||||
unbind();
|
|
||||||
OPENGL_CALL(glDeleteRenderbuffers(1, &_id));
|
|
||||||
_id = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
const unsigned int width;
|
|
||||||
const unsigned int height;
|
|
||||||
const GLenum format;
|
|
||||||
RenderBuffer(
|
|
||||||
GLenum format_,
|
|
||||||
unsigned int width_,
|
|
||||||
unsigned int height_
|
|
||||||
) :
|
|
||||||
format(format_),
|
|
||||||
width(width_),
|
|
||||||
height(height_),
|
|
||||||
RenderTarget(GL_RENDERBUFFER)
|
|
||||||
{ declare(); }
|
|
||||||
RenderBuffer(RenderBuffer&& rhs) :
|
|
||||||
width(rhs.width),
|
|
||||||
height(rhs.height),
|
|
||||||
format(rhs.format),
|
|
||||||
RenderTarget(std::move(rhs))
|
|
||||||
{}
|
|
||||||
RenderBuffer& operator=(RenderBuffer&&) = delete;
|
|
||||||
void bind() const override {
|
|
||||||
if (_id) {
|
|
||||||
OPENGL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, _id));
|
|
||||||
} else {
|
|
||||||
THROW(OpenGLObjectError(
|
|
||||||
OpenGLObjectError::Codes::INVALID_OBJECT,
|
|
||||||
"w/ RenderBuffer"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
void unbind() const override {
|
|
||||||
OPENGL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
class FrameBufferBase : public OpenGLObject {
|
|
||||||
private:
|
|
||||||
static bool texTypeIs2D(GLenum texType) {
|
|
||||||
switch(texType) {
|
|
||||||
case GL_TEXTURE_2D:
|
|
||||||
return true;
|
|
||||||
case GL_TEXTURE_1D:
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using AttachmentMap = std::unordered_map<GLenum, std::shared_ptr<RenderTarget>>;
|
|
||||||
AttachmentMap _attachments;
|
|
||||||
FrameBufferBase(GLenum target);
|
|
||||||
GLuint declare() override;
|
|
||||||
void remove() override;
|
|
||||||
std::shared_ptr<RenderTarget> detach(GLenum);
|
|
||||||
void attach(
|
|
||||||
GLenum attachment,
|
|
||||||
std::shared_ptr<RenderBuffer> renderbuffer
|
|
||||||
);
|
|
||||||
|
|
||||||
public:
|
|
||||||
const GLenum Target;
|
|
||||||
void bind() const override;
|
|
||||||
void unbind() const override;
|
|
||||||
GLenum status() const;
|
|
||||||
bool complete() const;
|
|
||||||
AttachmentMap getAllBuffers() const;
|
|
||||||
std::shared_ptr<RenderTarget> getBuffer(GLenum) const;
|
|
||||||
void attach(
|
|
||||||
GLenum attachment,
|
|
||||||
std::shared_ptr<Texture> texture,
|
|
||||||
unsigned int level=0
|
|
||||||
);
|
|
||||||
void attach(
|
|
||||||
GLenum attachment,
|
|
||||||
std::shared_ptr<Texture> texture,
|
|
||||||
unsigned int level,
|
|
||||||
unsigned int layer
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
class ReadFrameBuffer;
|
|
||||||
class WriteFrameBuffer;
|
|
||||||
|
|
||||||
class ReadFrameBuffer : public virtual FrameBufferBase {
|
|
||||||
friend WriteFrameBuffer;
|
|
||||||
protected:
|
|
||||||
using FrameBufferBase::_attachments;
|
|
||||||
GLenum _location;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using FrameBufferBase::attach;
|
|
||||||
ReadFrameBuffer();
|
|
||||||
ReadFrameBuffer& operator=(WriteFrameBuffer&&);
|
|
||||||
ReadFrameBuffer& operator=(ReadFrameBuffer&&);
|
|
||||||
std::shared_ptr<RenderTarget> getReadBuffer() const;
|
|
||||||
GLenum getReadLocation() const;
|
|
||||||
std::shared_ptr<RenderTarget> setReadBuffer(GLenum attachment);
|
|
||||||
template<typename T, typename... Args>
|
|
||||||
std::shared_ptr<RenderTarget> setReadBuffer(
|
|
||||||
GLenum attachment,
|
|
||||||
std::shared_ptr<T> target,
|
|
||||||
Args... args
|
|
||||||
) {
|
|
||||||
declare();
|
|
||||||
FrameBufferBase::attach(attachment, target, args...);
|
|
||||||
setReadBuffer(attachment);
|
|
||||||
return getReadBuffer();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
class WriteFrameBuffer : public virtual FrameBufferBase {
|
|
||||||
friend ReadFrameBuffer;
|
|
||||||
protected:
|
|
||||||
using DrawTexVec = std::vector<std::shared_ptr<Texture>>;
|
|
||||||
using FrameBufferBase::_attachments;
|
|
||||||
std::vector<GLenum> _locations;
|
|
||||||
|
|
||||||
public:
|
|
||||||
WriteFrameBuffer();
|
|
||||||
WriteFrameBuffer& operator=(ReadFrameBuffer&&);
|
|
||||||
WriteFrameBuffer& operator=(WriteFrameBuffer&&);
|
|
||||||
DrawTexVec getWriteBuffers() const;
|
|
||||||
std::vector<GLenum> getWriteLocations() const;
|
|
||||||
DrawTexVec setWriteBuffers(const std::vector<GLenum>& attachments);
|
|
||||||
std::shared_ptr<Texture> setWriteBuffer(GLenum attachment);
|
|
||||||
template<typename... T>
|
|
||||||
std::shared_ptr<Texture> setWriteBuffer(
|
|
||||||
GLenum attachment,
|
|
||||||
std::shared_ptr<Texture> texture,
|
|
||||||
T... args
|
|
||||||
) {
|
|
||||||
attach(attachment, texture, args...);
|
|
||||||
setWriteBuffer(attachment);
|
|
||||||
return std::static_pointer_cast<Texture>(_attachments.at(attachment));
|
|
||||||
}
|
|
||||||
|
|
||||||
RGBA<float> clearColorValue() const;
|
|
||||||
RGBA<float> clearColorValue(const RGBA<float>&);
|
|
||||||
RGBA<float> clearColorValue(float r, float g, float b, float a);
|
|
||||||
double clearDepthValue() const;
|
|
||||||
double clearDepthValue(double);
|
|
||||||
GLint clearStencilValue() const;
|
|
||||||
GLint clearStencilValue(GLint);
|
|
||||||
void clear(GLbitfield mask=(
|
|
||||||
GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT
|
|
||||||
)) const;
|
|
||||||
void clearColor() const;
|
|
||||||
void clearDepth() const;
|
|
||||||
void clearDepth(float) const;
|
|
||||||
void clearStencil() const;
|
|
||||||
void clearStencil(GLint) const;
|
|
||||||
void clearDepthStencil() const;
|
|
||||||
void clearDepthStencil(float, GLint) const;
|
|
||||||
};
|
|
||||||
|
|
||||||
class FrameBuffer : public ReadFrameBuffer, public WriteFrameBuffer {
|
|
||||||
protected:
|
|
||||||
using FrameBufferBase::_attachments;
|
|
||||||
using ReadFrameBuffer::_location;
|
|
||||||
using WriteFrameBuffer::_locations;
|
|
||||||
|
|
||||||
public:
|
|
||||||
FrameBuffer();
|
|
||||||
FrameBuffer& operator=(FrameBuffer&&);
|
|
||||||
FrameBuffer& operator=(ReadFrameBuffer&&);
|
|
||||||
FrameBuffer& operator=(WriteFrameBuffer&&);
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
#endif // _NB_FRAMEBUFFER
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_OPENGL_LOADER
|
|
||||||
#define _NB_OPENGL_LOADER
|
|
||||||
|
|
||||||
#include <glad/glad.h>
|
|
||||||
#include <GLFW/glfw3.h>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_IMAGE
|
|
||||||
#define _NB_IMAGE
|
|
||||||
|
|
||||||
#include <cstring>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct Color {};
|
|
||||||
|
|
||||||
struct Red : Color<Red> {};
|
|
||||||
struct Green : Color<Green> {};
|
|
||||||
struct Blue : Color<Blue> {};
|
|
||||||
struct Alpha : Color<Alpha> {};
|
|
||||||
|
|
||||||
struct Depth;
|
|
||||||
struct Stencil;
|
|
||||||
|
|
||||||
template<typename... T>
|
|
||||||
struct PixelChannel;
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct PixelChannel<T, Red> {
|
|
||||||
using type=T;
|
|
||||||
T value;
|
|
||||||
T& r=value;
|
|
||||||
};
|
|
||||||
template<typename T>
|
|
||||||
struct PixelChannel<T, Green> {
|
|
||||||
using type=T;
|
|
||||||
T value;
|
|
||||||
T& g=value;
|
|
||||||
};
|
|
||||||
template<typename T>
|
|
||||||
struct PixelChannel<T, Blue> {
|
|
||||||
using type=T;
|
|
||||||
T value;
|
|
||||||
T& b=value;
|
|
||||||
};
|
|
||||||
template<typename T>
|
|
||||||
struct PixelChannel<T, Alpha> {
|
|
||||||
using type=T;
|
|
||||||
T value;
|
|
||||||
T& a=value;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct PixelChannel<T, Depth> {
|
|
||||||
using type=T;
|
|
||||||
T value;
|
|
||||||
T& z=value;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct PixelChannel<uint8_t, Stencil> {
|
|
||||||
using type=uint8_t;
|
|
||||||
uint8_t value;
|
|
||||||
uint8_t& u=value;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T, typename... Channels>
|
|
||||||
struct Pixel : public PixelChannel<T, Channels>... {
|
|
||||||
Pixel() = default;
|
|
||||||
Pixel& operator=(const Pixel& rhs) {
|
|
||||||
((
|
|
||||||
[&](const typename PixelChannel<T, Channels>::type& val){
|
|
||||||
this->PixelChannel<T, Channels>::value = val;
|
|
||||||
}(rhs.PixelChannel<T, Channels>::value)
|
|
||||||
), ...);
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
Pixel(const Pixel& cpy)
|
|
||||||
: Pixel(cpy.PixelChannel<T, Channels>::value...) {}
|
|
||||||
|
|
||||||
Pixel(typename PixelChannel<T, Channels>::type... vals)
|
|
||||||
: PixelChannel<T, Channels>{vals}... {}
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename Ref>
|
|
||||||
struct PixelReference;
|
|
||||||
|
|
||||||
template<typename T, typename... Channels>
|
|
||||||
struct PixelReference<Pixel<T, Channels...>>
|
|
||||||
: public Pixel<T&, Channels...> {
|
|
||||||
using PixelType = Pixel<T, Channels...>;
|
|
||||||
using Base = Pixel<T&, Channels...>;
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
PixelReference(PixelType& pixel)
|
|
||||||
: Base(pixel.PixelChannel<T, Channels>::value...) {}
|
|
||||||
|
|
||||||
operator PixelType() {
|
|
||||||
return PixelType(this->PixelChannel<T&, Channels>::value...);
|
|
||||||
}
|
|
||||||
|
|
||||||
PixelReference& operator=(const PixelType& pixel) {
|
|
||||||
((
|
|
||||||
[&](const typename PixelChannel<T, Channels>::type& val){
|
|
||||||
this->PixelChannel<T&, Channels>::value = val;
|
|
||||||
}(pixel.PixelChannel<T, Channels>::value)
|
|
||||||
), ...);
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
using RGBA = Pixel<T, Red, Green, Blue, Alpha>;
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
using RGB = Pixel<T, Red, Green, Blue>;
|
|
||||||
|
|
||||||
class ImageError : public Error<ImageError> {
|
|
||||||
protected:
|
|
||||||
using Base = Error<ImageError>;
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
public:
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, OUT_OF_BOUNDS
|
|
||||||
};
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
class Image;
|
|
||||||
|
|
||||||
template<typename T, typename... Channels>
|
|
||||||
class Image<Pixel<T, Channels...>> {
|
|
||||||
private:
|
|
||||||
Error<> sizeCompare(const Image& rhs) {
|
|
||||||
const std::string errmsg = "Cannot assign images of different size";
|
|
||||||
if (width != rhs.width) {
|
|
||||||
return Error<>(
|
|
||||||
Error<>::VALUE_ERROR,
|
|
||||||
errmsg+"[ Width: "+std::to_string(width)+\
|
|
||||||
" != "+std::to_string(rhs.width)+" ]"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (height != rhs.height) {
|
|
||||||
return Error<>(
|
|
||||||
Error<>::VALUE_ERROR,
|
|
||||||
errmsg+"[ Width: "+std::to_string(width)+\
|
|
||||||
" != "+std::to_string(rhs.width)+" ]"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return Error<>("NoError");
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Codes = ImageError::Codes;
|
|
||||||
bool _data_managed;
|
|
||||||
T* _data;
|
|
||||||
Image(unsigned int x, unsigned int y, T* data, bool managed)
|
|
||||||
: width(x), height(y), _data(data), _data_managed(managed) {}
|
|
||||||
void clear() {
|
|
||||||
if (_data_managed) {
|
|
||||||
delete[] _data;
|
|
||||||
_data_managed = false;
|
|
||||||
}
|
|
||||||
_data = nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using PixelType = Pixel<T, Channels...>;
|
|
||||||
static constexpr size_t NumberChannels = sizeof...(Channels);
|
|
||||||
const unsigned int width;
|
|
||||||
const unsigned int height;
|
|
||||||
static Image CreateImageStorage(
|
|
||||||
unsigned int width,
|
|
||||||
unsigned int height,
|
|
||||||
T* data=nullptr
|
|
||||||
) {
|
|
||||||
unsigned int data_size = NumberChannels*width*height*sizeof(T);
|
|
||||||
T* data_ptr = new T[data_size];
|
|
||||||
Image ret(width, height, data_ptr, true);
|
|
||||||
if (data) {
|
|
||||||
std::memcpy(data_ptr, data, data_size);
|
|
||||||
} else {
|
|
||||||
std::memset(data_ptr, 0x00, data_size);
|
|
||||||
}
|
|
||||||
ret._data_managed = true;
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
Image(unsigned int x, unsigned int y, T* data=nullptr)
|
|
||||||
: width(x), height(y), _data(data), _data_managed(false) {}
|
|
||||||
Image(const Image& cpy)
|
|
||||||
: Image(cpy.width, cpy.height) {
|
|
||||||
*this = cpy;
|
|
||||||
}
|
|
||||||
Image(Image&& mv)
|
|
||||||
: Image(mv.width, mv.height) {
|
|
||||||
*this = std::move(mv);
|
|
||||||
}
|
|
||||||
Image& operator=(const Image& cpy) {
|
|
||||||
if (_data_managed) {
|
|
||||||
THROW(Error<>(Error<>::OVERWRITE_ERROR));
|
|
||||||
}
|
|
||||||
const Error<> sizeErr = sizeCompare(cpy);
|
|
||||||
if (sizeErr.code!=1) { THROW(sizeErr); }
|
|
||||||
if (!cpy._data_managed) {
|
|
||||||
_data = cpy._data;
|
|
||||||
_data_managed = false;
|
|
||||||
} else {
|
|
||||||
*this = cpy.copy();
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
Image& operator=(Image&& mv) {
|
|
||||||
if (_data_managed) {
|
|
||||||
THROW(Error<>(Error<>::OVERWRITE_ERROR));
|
|
||||||
}
|
|
||||||
const Error<> sizeErr = sizeCompare(mv);
|
|
||||||
if (sizeErr.code!=1) { THROW(sizeErr); }
|
|
||||||
_data = mv._data;
|
|
||||||
_data_managed = mv._data_managed;
|
|
||||||
mv._data_managed = false;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual ~Image() {
|
|
||||||
clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
const T* data() const { return _data; }
|
|
||||||
Image<PixelType> copy() const {
|
|
||||||
return CreateImageStorage(width, height, _data);
|
|
||||||
}
|
|
||||||
PixelReference<PixelType> at(unsigned int x, unsigned int y) {
|
|
||||||
if (!(x<width) || !(y<height)) {
|
|
||||||
std::string note = "w/ ("+std::to_string(x);
|
|
||||||
note += ", "+std::to_string(y) + ") >= (";
|
|
||||||
note += std::to_string(width)+", "+std::to_string(height);
|
|
||||||
note += ")";
|
|
||||||
THROW(ImageError(
|
|
||||||
Codes::OUT_OF_BOUNDS,
|
|
||||||
note
|
|
||||||
));
|
|
||||||
}
|
|
||||||
auto coord = y*height+x;
|
|
||||||
return PixelReference<PixelType>(
|
|
||||||
_data[coord*NumberChannels+Find<Channels, Channels...>::value-1]...
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
|
|
||||||
#endif // _NB_IMAGE
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_MESH
|
|
||||||
#define _NB_MESH
|
|
||||||
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
|
|
||||||
#include <NBGraphics/Buffers.hpp>
|
|
||||||
#include <NBGraphics/VertexArray.hpp>
|
|
||||||
#include <NBGraphics/VertexData.hpp>
|
|
||||||
|
|
||||||
namespace nb{
|
|
||||||
|
|
||||||
class Mesh {
|
|
||||||
protected:
|
|
||||||
const GLenum _primitive;
|
|
||||||
const unsigned int _count;
|
|
||||||
std::shared_ptr<VAO> _vao;
|
|
||||||
|
|
||||||
public:
|
|
||||||
Mesh(
|
|
||||||
VertexDataPointerList vao,
|
|
||||||
unsigned int count,
|
|
||||||
GLenum primitive=GL_TRIANGLES
|
|
||||||
);
|
|
||||||
Mesh(GLenum primitive, const std::shared_ptr<VAO>& vertex_array, unsigned int count);
|
|
||||||
Mesh(GLenum primitive, const VertexData& vertex_data, unsigned int count);
|
|
||||||
Mesh(
|
|
||||||
GLenum primitive,
|
|
||||||
const ByteVector& data,
|
|
||||||
unsigned int count,
|
|
||||||
const std::vector<VertexAttribute>& attributes
|
|
||||||
);
|
|
||||||
|
|
||||||
Mesh(Mesh&&);
|
|
||||||
Mesh(const Mesh&&) = delete;
|
|
||||||
Mesh& operator=(Mesh&&) = delete;
|
|
||||||
Mesh& operator=(const Mesh&) = delete;
|
|
||||||
|
|
||||||
inline virtual void draw() const { this->draw(_count); }
|
|
||||||
inline virtual void draw(unsigned int count) const { this->draw(0, count); }
|
|
||||||
virtual void draw(unsigned int offset, unsigned int count) const;
|
|
||||||
inline GLenum primitive() const { return _primitive; }
|
|
||||||
inline unsigned int count() const { return _count; }
|
|
||||||
inline std::shared_ptr<VAO> vao() const { return _vao; }
|
|
||||||
};
|
|
||||||
|
|
||||||
class InstancedMesh : public Mesh {
|
|
||||||
protected:
|
|
||||||
using Mesh::_primitive;
|
|
||||||
using Mesh::_count;
|
|
||||||
using Mesh::_vao;
|
|
||||||
|
|
||||||
public:
|
|
||||||
virtual void draw(unsigned int offset, unsigned int count) const;
|
|
||||||
};
|
|
||||||
|
|
||||||
class IndexedMesh : public Mesh {
|
|
||||||
protected:
|
|
||||||
std::shared_ptr<ElementBuffer> _ebo;
|
|
||||||
|
|
||||||
public:
|
|
||||||
template<typename T>
|
|
||||||
IndexedMesh(
|
|
||||||
GLenum primitive,
|
|
||||||
const ByteVector& data,
|
|
||||||
const std::vector<VertexAttribute>& attributes,
|
|
||||||
const std::vector<T>& indices
|
|
||||||
) : Mesh(primitive, data, indices.size(), attributes) {
|
|
||||||
_vao->bind();
|
|
||||||
_ebo = std::make_shared<ElementBuffer>(indices);
|
|
||||||
}
|
|
||||||
|
|
||||||
using Mesh::draw;
|
|
||||||
virtual void draw(unsigned int offset, unsigned int count) const;
|
|
||||||
};
|
|
||||||
|
|
||||||
class InstancedIndexedMesh : virtual public IndexedMesh {};
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_OGL_OBJECTS
|
|
||||||
#define _NB_OGL_OBJECTS
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
#include <NBCore/Utils.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
typedef ConstantMap<GLenum, std::string> GLEnumTableType;
|
|
||||||
|
|
||||||
extern const GLEnumTableType GLenumTable;
|
|
||||||
extern const ConstantMap<TypeCodes, GLint> TypeToGLSL;
|
|
||||||
|
|
||||||
class OpenGLError : public Error<OpenGLError> {
|
|
||||||
using Base = Error<OpenGLError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
NO_ERROR = GL_NO_ERROR,
|
|
||||||
INVALID_ENUM = GL_INVALID_ENUM,
|
|
||||||
INVALID_VALUE = GL_INVALID_VALUE,
|
|
||||||
INVALID_OPERATION = GL_INVALID_OPERATION,
|
|
||||||
INVALID_FRAMEBUFFER_OPERATION = GL_INVALID_FRAMEBUFFER_OPERATION,
|
|
||||||
OUT_OF_MEMORY = GL_OUT_OF_MEMORY,
|
|
||||||
STACK_UNDERFLOW = GL_STACK_UNDERFLOW,
|
|
||||||
STACK_OVERFLOW = GL_STACK_OVERFLOW
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
static OpenGLError status();
|
|
||||||
static OpenGLError status(const std::string& note);
|
|
||||||
};
|
|
||||||
|
|
||||||
class OpenGLObjectError : public Error<OpenGLObjectError> {
|
|
||||||
using Base = Error<OpenGLObjectError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, HANGING_OBJECT, INVALID_OBJECT, INVALID_CONTEXT
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
class OpenGLObject {
|
|
||||||
public:
|
|
||||||
OpenGLObject(const OpenGLObject&) = delete;
|
|
||||||
OpenGLObject& operator=(const OpenGLObject&) = delete;
|
|
||||||
OpenGLObject(OpenGLObject&&);
|
|
||||||
OpenGLObject& operator=(OpenGLObject&&);
|
|
||||||
virtual ~OpenGLObject() {};
|
|
||||||
|
|
||||||
virtual void bind() const = 0;
|
|
||||||
virtual void unbind() const = 0;
|
|
||||||
GLuint id() const { return _id; }
|
|
||||||
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Codes = OpenGLObjectError::Codes;
|
|
||||||
OpenGLObject();
|
|
||||||
|
|
||||||
void checkObjectContextValidity();
|
|
||||||
virtual GLuint declare() = 0;
|
|
||||||
virtual void remove() = 0;
|
|
||||||
|
|
||||||
const GLFWwindow* const _arena;
|
|
||||||
GLuint _id = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#ifndef OPENGL_CALL
|
|
||||||
#ifdef _NB_MONITOR_OPENGL_CALLS
|
|
||||||
namespace NB_OPENGL_CALL_MONITORING {
|
|
||||||
template<typename Fn>
|
|
||||||
inline auto run_expression(
|
|
||||||
const std::string& file,
|
|
||||||
unsigned int line,
|
|
||||||
Fn fn
|
|
||||||
) {
|
|
||||||
auto check_ = [file, line](const std::string& note="") {
|
|
||||||
const auto no_err = nb::OpenGLError::NO_ERROR;
|
|
||||||
auto stat = nb::OpenGLError::status(note);
|
|
||||||
if (stat.code != no_err) {
|
|
||||||
THROW_W_CODE_LOC(file, line, stat);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if constexpr(std::is_same_v<std::invoke_result_t<Fn>, void>) {
|
|
||||||
check_("Pre-call state");
|
|
||||||
fn();
|
|
||||||
check_("Post-call state");
|
|
||||||
} else {
|
|
||||||
check_("Pre-call state");
|
|
||||||
auto ret = fn();
|
|
||||||
check_("Post-call state");
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
#define OPENGL_CALL(expression) NB_OPENGL_CALL_MONITORING::run_expression(\
|
|
||||||
__FILE__,\
|
|
||||||
__LINE__,\
|
|
||||||
[&]() {return expression;}\
|
|
||||||
)
|
|
||||||
#else
|
|
||||||
#define OPENGL_CALL(x) x
|
|
||||||
#endif // _NB_MONITOR_OPENGL_CALLS
|
|
||||||
|
|
||||||
#endif // OPENGL_CALL
|
|
||||||
|
|
||||||
#endif // _NB_OGL_OBJECTS
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_SHADER
|
|
||||||
#define _NB_SHADER
|
|
||||||
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
#include <NBCore/Utils.hpp>
|
|
||||||
|
|
||||||
#include <NBGraphics/Buffers.hpp>
|
|
||||||
#include <NBGraphics/OGLObjects.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
class ShaderError : public Error<ShaderError> {
|
|
||||||
using Base = Error<ShaderError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
class ProgramError : public Error<ProgramError> {
|
|
||||||
using Base = Error<ProgramError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, LINKING_ERROR
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
enum OpenGLProfiles {
|
|
||||||
Core,
|
|
||||||
Compatibility,
|
|
||||||
ES
|
|
||||||
};
|
|
||||||
|
|
||||||
class Shader : public OpenGLObject {
|
|
||||||
using Base = OpenGLObject;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
using Base::id;
|
|
||||||
Shader(GLenum, const std::string&);
|
|
||||||
Shader(GLenum, const std::vector<std::string>&);
|
|
||||||
Shader(Shader&&);
|
|
||||||
Shader& operator=(Shader&&) = delete;
|
|
||||||
~Shader() { remove(); }
|
|
||||||
operator bool();
|
|
||||||
virtual void bind() const override { /* TODO: Some warning of some kind perhaps*/ }
|
|
||||||
virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ }
|
|
||||||
bool success() const;
|
|
||||||
GLint status(GLenum) const;
|
|
||||||
std::string log() const;
|
|
||||||
const GLenum target;
|
|
||||||
friend Base;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Base::_id;
|
|
||||||
GLint _success;
|
|
||||||
std::vector<std::string> _sources;
|
|
||||||
|
|
||||||
virtual void compile() {
|
|
||||||
int num_srcs = _sources.size();
|
|
||||||
std::vector<char*> src_ptrs(num_srcs);
|
|
||||||
for (int i=0; i < num_srcs; ++i) {
|
|
||||||
src_ptrs[i] = _sources[i].data();
|
|
||||||
}
|
|
||||||
OPENGL_CALL(glShaderSource(_id, num_srcs, src_ptrs.data(), NULL));
|
|
||||||
OPENGL_CALL(glCompileShader(_id));
|
|
||||||
_success = status(GL_COMPILE_STATUS);
|
|
||||||
if (!_success) {
|
|
||||||
WARN(log(), 0x0FE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual GLuint declare() override {
|
|
||||||
if (!_id) {
|
|
||||||
_id = _id = OPENGL_CALL(glCreateShader(target));
|
|
||||||
}
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual void remove() override {
|
|
||||||
if (_id) {
|
|
||||||
OPENGL_CALL(glDeleteShader(_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
class Program : public OpenGLObject {
|
|
||||||
using Base = OpenGLObject;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
using Base::id;
|
|
||||||
Program(SharedVector<Shader>);
|
|
||||||
Program(Program&&);
|
|
||||||
Program& operator=(Program&&) = delete;
|
|
||||||
operator bool();
|
|
||||||
~Program() { remove(); }
|
|
||||||
void bind() const override {
|
|
||||||
OPENGL_CALL(glUseProgram(_id));
|
|
||||||
}
|
|
||||||
void unbind() const override { /* TODO: Some warning of some kind perhaps*/ }
|
|
||||||
GLint status(GLenum) const;
|
|
||||||
std::string log() const;
|
|
||||||
void setUniform(const std::string& blockname, std::shared_ptr<UniformBuffer>);
|
|
||||||
void setUniformBinding(const std::string& blockname, GLuint index);
|
|
||||||
GLuint getUniformBinding(const std::string& blockname) const;
|
|
||||||
|
|
||||||
friend Base;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Base::_id;
|
|
||||||
GLint _success;
|
|
||||||
std::unordered_map<std::string, GLuint> _uniformBindings;
|
|
||||||
virtual GLuint declare() override {
|
|
||||||
if (!_id) {
|
|
||||||
_id = OPENGL_CALL(glCreateProgram());
|
|
||||||
}
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
virtual void remove() override {
|
|
||||||
if (_id) {
|
|
||||||
OPENGL_CALL(glDeleteProgram(_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -1,267 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_TEXTURES
|
|
||||||
#define _NB_TEXTURES
|
|
||||||
|
|
||||||
#include <NBGraphics/Buffers.hpp>
|
|
||||||
#include <NBGraphics/Image.hpp>
|
|
||||||
#include <NBGraphics/OGLObjects.hpp>
|
|
||||||
|
|
||||||
/*! @file Textures.hpp */
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
class TextureBuffer : public virtual Buffer {
|
|
||||||
public:
|
|
||||||
TextureBuffer() : Buffer(GL_TEXTURE_BUFFER) {}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
/*!
|
|
||||||
@brief An OpenGL object that may be rendered to within a Framebuffer.
|
|
||||||
*/
|
|
||||||
class RenderTarget : public OpenGLObject {
|
|
||||||
protected:
|
|
||||||
using Base = OpenGLObject;
|
|
||||||
using Base::_id;
|
|
||||||
RenderTarget(GLenum target) : Target(target) {}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::id;
|
|
||||||
RenderTarget(RenderTarget&& mv);
|
|
||||||
RenderTarget& operator=(RenderTarget&& mv);
|
|
||||||
const GLenum Target;
|
|
||||||
};
|
|
||||||
|
|
||||||
/*!
|
|
||||||
@brief An OpenGL Target object
|
|
||||||
*/
|
|
||||||
class Texture : public RenderTarget {
|
|
||||||
protected:
|
|
||||||
using Base = RenderTarget;
|
|
||||||
using Base::_id;
|
|
||||||
Texture(GLenum);
|
|
||||||
virtual GLuint declare() override {
|
|
||||||
if (!_id) {
|
|
||||||
OPENGL_CALL(glGenTextures(1, &_id));
|
|
||||||
}
|
|
||||||
bind();
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
virtual void remove() override {
|
|
||||||
if (_id) {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(glDeleteTextures(0, &_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::id;
|
|
||||||
using Base::Target;
|
|
||||||
Texture(Texture&& mv);
|
|
||||||
Texture& operator=(Texture&& mv);
|
|
||||||
|
|
||||||
void bind() const override {
|
|
||||||
if (_id) {
|
|
||||||
OPENGL_CALL(glBindTexture(Target, _id));
|
|
||||||
} else {
|
|
||||||
THROW(OpenGLObjectError(
|
|
||||||
OpenGLObjectError::Codes::INVALID_OBJECT,
|
|
||||||
"w/ Texture"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
void unbind() const override {
|
|
||||||
OPENGL_CALL(glBindTexture(Target, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
void parameter(GLenum param_, const T& val_);
|
|
||||||
void parameter(GLenum param_, const float& val_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glTexParameterf(Target, param_, val_)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
void parameter(GLenum param_, const int& val_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glTexParameteri(Target, param_, val_)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
void parameter(GLenum param_, const std::vector<float>& val_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glTexParameterfv(Target, param_, val_.data())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
void parameter(GLenum param_, const std::vector<int>& val_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glTexParameteriv(Target, param_, val_.data())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
void parameter(GLenum param_, const std::vector<unsigned int>& val_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glTexParameterIuiv(Target, param_, val_.data())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
void generateMipmaps() const {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glGenerateMipmap(Target)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct OGLPixelFormat;
|
|
||||||
|
|
||||||
template<typename T, typename... Channels>
|
|
||||||
struct OGLPixelFormat<Pixel<T, Channels...>>;
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> {
|
|
||||||
static constexpr GLenum glBase = GL_RGBA;
|
|
||||||
static constexpr GLenum glFormat = GL_RGBA8UI;
|
|
||||||
static constexpr GLenum glData = GL_UNSIGNED_BYTE;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct OGLPixelFormat<Pixel<float, Red, Green, Blue, Alpha>> {
|
|
||||||
static constexpr GLenum glBase = GL_RGBA;
|
|
||||||
static constexpr GLenum glFormat = GL_RGBA32F;
|
|
||||||
static constexpr GLenum glData = GL_FLOAT;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue>> {
|
|
||||||
static constexpr GLenum glBase = GL_RGB;
|
|
||||||
static constexpr GLenum glFormat = GL_RGB8UI;
|
|
||||||
static constexpr GLenum glData = GL_UNSIGNED_BYTE;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct OGLPixelFormat<Pixel<float, Red, Green, Blue>> {
|
|
||||||
static constexpr GLenum glBase = GL_RGB;
|
|
||||||
static constexpr GLenum glFormat = GL_RGB32F;
|
|
||||||
static constexpr GLenum glData = GL_FLOAT;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct OGLPixelFormat<Pixel<float, Red, Green>> {
|
|
||||||
static constexpr GLenum glBase = GL_RG;
|
|
||||||
static constexpr GLenum glFormat = GL_RG32F;
|
|
||||||
static constexpr GLenum glData = GL_FLOAT;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct OGLPixelFormat<Pixel<float, Red>> {
|
|
||||||
static constexpr GLenum glBase = GL_RED;
|
|
||||||
static constexpr GLenum glFormat = GL_R32F;
|
|
||||||
static constexpr GLenum glData = GL_FLOAT;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
class Texture2D;
|
|
||||||
|
|
||||||
template<typename T, typename... Channels>
|
|
||||||
class Texture2D<Pixel<T, Channels...>> : public Texture {
|
|
||||||
protected:
|
|
||||||
using Texture::Texture;
|
|
||||||
using PixelType = Pixel<T, Channels...>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Texture::generateMipmaps;
|
|
||||||
Texture2D() : Texture(GL_TEXTURE_2D) {}
|
|
||||||
Texture2D(Texture2D&& cpy) {
|
|
||||||
*this = std::move(cpy);
|
|
||||||
}
|
|
||||||
Texture2D& operator=(Texture2D&& rhs) {
|
|
||||||
return Texture::operator=(std::move(rhs));
|
|
||||||
}
|
|
||||||
void setLayer(const Image<PixelType>& img, unsigned int layer) {
|
|
||||||
using Format = OGLPixelFormat<PixelType>;
|
|
||||||
declare();
|
|
||||||
auto data = img.data();
|
|
||||||
OPENGL_CALL(glTexImage2D(
|
|
||||||
Target,
|
|
||||||
layer,
|
|
||||||
Format::glFormat,
|
|
||||||
img.width,
|
|
||||||
img.height,
|
|
||||||
0,
|
|
||||||
Format::glBase,
|
|
||||||
Format::glData,
|
|
||||||
data ? data : nullptr
|
|
||||||
));
|
|
||||||
}
|
|
||||||
void setTexture(const Image<PixelType>& img, bool generateMipmap=true) {
|
|
||||||
setLayer(img, 0);
|
|
||||||
if (generateMipmap) { generateMipmaps(); }
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
class Texture1D;
|
|
||||||
|
|
||||||
template<typename T, typename... Channels>
|
|
||||||
class Texture1D<Pixel<T, Channels...>> : public Texture {
|
|
||||||
protected:
|
|
||||||
using Texture::Texture;
|
|
||||||
using PixelType = Pixel<T, Channels...>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Texture::generateMipmaps;
|
|
||||||
Texture1D() : Texture(GL_TEXTURE_1D) {}
|
|
||||||
Texture1D(Texture1D&& cpy) {
|
|
||||||
*this = std::move(cpy);
|
|
||||||
}
|
|
||||||
Texture1D& operator=(Texture1D&& rhs) {
|
|
||||||
return Texture::operator=(std::move(rhs));
|
|
||||||
}
|
|
||||||
void setLayer(const Image<PixelType>& tex, unsigned int layer) {
|
|
||||||
if (tex.height != 1) {
|
|
||||||
THROW(Error<>(
|
|
||||||
Error<>::VALUE_ERROR,
|
|
||||||
"Image must be of height 1"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
using Format = OGLPixelFormat<PixelType>;
|
|
||||||
declare();
|
|
||||||
auto data = tex.data();
|
|
||||||
OPENGL_CALL(glTexImage1D(
|
|
||||||
Target,
|
|
||||||
layer,
|
|
||||||
Format::glFormat,
|
|
||||||
tex.width,
|
|
||||||
0,
|
|
||||||
Format::glBase,
|
|
||||||
Format::glData,
|
|
||||||
data ? data : nullptr
|
|
||||||
));
|
|
||||||
}
|
|
||||||
void setTexture(const Image<PixelType>& tex, bool generateMipmap=true) {
|
|
||||||
setLayer(tex, 0);
|
|
||||||
if (generateMipmap) { generateMipmaps(); }
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
class Texture1DArray;
|
|
||||||
|
|
||||||
template <typename... T>
|
|
||||||
class Texture1DArray<Pixel<T...>> : public Texture {
|
|
||||||
protected:
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Texture::generateMipmaps;
|
|
||||||
Texture1DArray() : Texture(GL_TEXTURE_1D_ARRAY) {
|
|
||||||
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#endif // _NB_TEXTURES
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_VERTEX_ARRAY
|
|
||||||
#define _NB_VERTEX_ARRAY
|
|
||||||
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
|
|
||||||
#include <NBGraphics/Buffers.hpp>
|
|
||||||
#include <NBGraphics/OGLObjects.hpp>
|
|
||||||
#include <NBGraphics/VertexData.hpp>
|
|
||||||
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
static uint8_t GLSLTypeSize(GLenum type) {
|
|
||||||
switch(type) {
|
|
||||||
case GL_SHORT:
|
|
||||||
case GL_UNSIGNED_SHORT:
|
|
||||||
case GL_HALF_FLOAT:
|
|
||||||
return 2;
|
|
||||||
break;
|
|
||||||
case GL_INT:
|
|
||||||
case GL_UNSIGNED_INT:
|
|
||||||
case GL_FLOAT:
|
|
||||||
return 4;
|
|
||||||
break;
|
|
||||||
case GL_DOUBLE:
|
|
||||||
return 8;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
return 1;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool isIndexInVertexAttribute(int i, const VertexAttribute& va) {
|
|
||||||
if ((i -= va.layout.offset) < 0) { return false; }
|
|
||||||
return (i%va.layout.stride) < GLSLTypeSize(TypeToGLSL[va.type]) * va.size;
|
|
||||||
}
|
|
||||||
|
|
||||||
typedef std::vector<VertexData> VertexDataList;
|
|
||||||
typedef std::vector<VertexDataPointer> VertexDataPointerList;
|
|
||||||
|
|
||||||
class VAOError : public Error<VAOError> {
|
|
||||||
using Base = Error<VAOError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, INVALID_ATTRIBUTE
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
class VAO : public OpenGLObject {
|
|
||||||
using Base = OpenGLObject;
|
|
||||||
using Codes = VAOError::Codes;
|
|
||||||
|
|
||||||
protected:
|
|
||||||
using Base::_id;
|
|
||||||
VertexDataPointerList _vertexdata;
|
|
||||||
|
|
||||||
virtual void remove() override {
|
|
||||||
if(_id) {
|
|
||||||
disable();
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(glDeleteVertexArrays(1, &_id));
|
|
||||||
_id = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
virtual GLuint declare() override {
|
|
||||||
if (!_id) {
|
|
||||||
OPENGL_CALL(glGenVertexArrays(1, &_id));
|
|
||||||
}
|
|
||||||
bind();
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
VAO() = default;
|
|
||||||
VAO(const VertexDataPointerList&);
|
|
||||||
VAO(VAO&&);
|
|
||||||
|
|
||||||
VAO& operator=(VAO&&);
|
|
||||||
|
|
||||||
virtual void bind() const override {
|
|
||||||
if(_id) {
|
|
||||||
OPENGL_CALL(glBindVertexArray(_id));
|
|
||||||
} else {
|
|
||||||
THROW(OpenGLObjectError(
|
|
||||||
OpenGLObjectError::Codes::INVALID_OBJECT,
|
|
||||||
"w/ VertexArrayObject"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
virtual void unbind() const override {
|
|
||||||
OPENGL_CALL(glBindVertexArray(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
VertexDataPointerList attributes() const;
|
|
||||||
VertexDataPointerList attributes(const VertexDataPointerList&);
|
|
||||||
VertexDataPointerList attributes(const VertexDataList&);
|
|
||||||
VertexDataPointer attribute(GLuint) const;
|
|
||||||
void enable() const;
|
|
||||||
void enable(GLuint) const;
|
|
||||||
void disable() const;
|
|
||||||
void disable(GLuint) const;
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
class VertexError : public Error<VertexError> {
|
|
||||||
protected:
|
|
||||||
using Base = Error<VertexError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, MISALIGNED_DATA
|
|
||||||
};
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#endif // _NB_VERTEX_ARRAY
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_VERTEX_DATA
|
|
||||||
#define _NB_VERTEX_DATA
|
|
||||||
|
|
||||||
#include <memory>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include <NBCore/TypeTraits.hpp>
|
|
||||||
#include <NBCore/Utils.hpp>
|
|
||||||
#include <NBGraphics/Buffers.hpp>
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
|
|
||||||
// #include <NBGraphics/VertexArray.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
struct VertexAtrributeLayout {
|
|
||||||
unsigned int offset = 0;
|
|
||||||
int stride = 0;
|
|
||||||
unsigned int divisor = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct VertexAttribute {
|
|
||||||
unsigned int size;
|
|
||||||
TypeCodes type;
|
|
||||||
bool normalized;
|
|
||||||
VertexAtrributeLayout layout;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct VertexData {
|
|
||||||
std::shared_ptr<Buffer> data;
|
|
||||||
std::vector<VertexAttribute> attributes;
|
|
||||||
VertexData(std::shared_ptr<Buffer>, const std::vector<VertexAttribute>&);
|
|
||||||
VertexData(const ByteVector&, const std::vector<VertexAttribute>&);
|
|
||||||
};
|
|
||||||
|
|
||||||
struct VertexDataPointer {
|
|
||||||
std::shared_ptr<VertexData> vertexdata;
|
|
||||||
unsigned int index;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
#endif
|
|
||||||
@@ -1,272 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#ifndef _NB_WINDOW
|
|
||||||
#define _NB_WINDOW
|
|
||||||
|
|
||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
#include <NBGraphics/OGLObjects.hpp>
|
|
||||||
|
|
||||||
#include <array>
|
|
||||||
#include <functional>
|
|
||||||
#include <memory>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
#include <NBCore/Utils.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
class GLFWError : public Error<GLFWError> {
|
|
||||||
using Base = Error<GLFWError>;
|
|
||||||
|
|
||||||
public:
|
|
||||||
using Base::Base;
|
|
||||||
|
|
||||||
enum Codes : unsigned int {
|
|
||||||
UNDEFINED, INIT_FAILED, GLFW_INTIALIZED, GLAD_FAILED,
|
|
||||||
NOT_MAIN, WINDOW_FAILED
|
|
||||||
};
|
|
||||||
|
|
||||||
static const std::string type;
|
|
||||||
static const ErrorCodeMap ErrorMessages;
|
|
||||||
};
|
|
||||||
|
|
||||||
class OGLWindow;
|
|
||||||
|
|
||||||
enum WindowCallbacks {
|
|
||||||
KEY, CHAR, CHAR_MODS, MOUSE_BUTTON, CURSOR_POS, CURSOR_ENTER,
|
|
||||||
SCROLL, DROP, WINDOW_POS, WINDOW_SIZE, WINDOW_CLOSE, WINDOW_REFRESH,
|
|
||||||
WINDOW_FOCUS, WINDOW_ICONIFY, WINDOW_MAX, FRAMEBUFFER_SIZE, WINDOW_SCALE,
|
|
||||||
};
|
|
||||||
|
|
||||||
template<WindowCallbacks>
|
|
||||||
struct OGLWindowCallbacks;
|
|
||||||
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::KEY> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int, int, int, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::CHAR> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, unsigned int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::CHAR_MODS> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, unsigned int, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::CURSOR_ENTER> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::CURSOR_POS> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, double, double)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::MOUSE_BUTTON> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int, int, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::SCROLL> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, double, double)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::DROP> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int, const char**)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_POS> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_SIZE> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_CLOSE> {
|
|
||||||
using type = typename std::function<void(OGLWindow*)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_REFRESH> {
|
|
||||||
using type = typename std::function<void(OGLWindow*)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_FOCUS> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_ICONIFY> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_MAX> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::FRAMEBUFFER_SIZE> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int, int)>;
|
|
||||||
};
|
|
||||||
template<>
|
|
||||||
struct OGLWindowCallbacks<WindowCallbacks::WINDOW_SCALE> {
|
|
||||||
using type = typename std::function<void(OGLWindow*, int)>;
|
|
||||||
};
|
|
||||||
|
|
||||||
class OGLWindow {
|
|
||||||
using GLFWHint = std::array<int, 2>;
|
|
||||||
private:
|
|
||||||
static inline void CheckForMainThread() {
|
|
||||||
if (nb::CurrentTID != nb::MainTID) {
|
|
||||||
THROW(GLFWError(GLFWError::Codes::NOT_MAIN));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
static std::atomic<unsigned int> _count;
|
|
||||||
static std::atomic<bool> _glfwInitialized;
|
|
||||||
static thread_local GLFWwindow* _currWindow;
|
|
||||||
static thread_local const GLFWwindow* _currArena;
|
|
||||||
|
|
||||||
static void SetHintInteger(const std::array<int, 2>&);
|
|
||||||
static void SetHintString(const std::tuple<int, std::string>&);
|
|
||||||
|
|
||||||
std::string _title;
|
|
||||||
GLFWwindow* _window_ptr;
|
|
||||||
const GLFWwindow* _arena;
|
|
||||||
|
|
||||||
OGLWindow(
|
|
||||||
unsigned int,
|
|
||||||
unsigned int,
|
|
||||||
const std::string&,
|
|
||||||
const std::vector<std::array<int, 2>>& integerWindowHints,
|
|
||||||
const std::vector<std::tuple<int, std::string>>& stringWindowHints={},
|
|
||||||
GLFWwindow* sharingContext = NULL
|
|
||||||
);
|
|
||||||
GLFWwindow* makeCurrent() const;
|
|
||||||
void detachWindow();
|
|
||||||
|
|
||||||
public:
|
|
||||||
|
|
||||||
static inline bool IsGLFWInitialized() { return _glfwInitialized; }
|
|
||||||
static bool InitGLFW(const std::vector<GLFWHint>& hints={});
|
|
||||||
static bool TerminateGLFW();
|
|
||||||
static inline GLFWwindow* GetCurrentWindow() { return _currWindow; }
|
|
||||||
static inline const GLFWwindow* GetCurrentObjectArena() { return _currArena; }
|
|
||||||
static GLFWwindow* MakeCurrent(const std::shared_ptr<OGLWindow>&);
|
|
||||||
static inline GLFWwindow* DropCurrent() { return MakeCurrent(nullptr); }
|
|
||||||
static void DestroyWindow(std::shared_ptr<OGLWindow>&);
|
|
||||||
static std::shared_ptr<OGLWindow> CreateWindow(
|
|
||||||
unsigned int x,
|
|
||||||
unsigned int y,
|
|
||||||
const std::string& title,
|
|
||||||
const std::vector<std::array<int, 2>>& integerHints={},
|
|
||||||
const std::vector<std::tuple<int, std::string>>& stringHints={}
|
|
||||||
);
|
|
||||||
static std::shared_ptr<OGLWindow> CreateSharedWindow(
|
|
||||||
unsigned int x,
|
|
||||||
unsigned int y,
|
|
||||||
const std::string& title,
|
|
||||||
std::shared_ptr<OGLWindow> sharingWindow,
|
|
||||||
const std::vector<std::array<int, 2>>& integerHints={},
|
|
||||||
const std::vector<std::tuple<int, std::string>>& stringHints={}
|
|
||||||
);
|
|
||||||
|
|
||||||
OGLWindow(OGLWindow&&) = delete;
|
|
||||||
OGLWindow(const OGLWindow&) = delete;
|
|
||||||
~OGLWindow();
|
|
||||||
inline bool operator==(const OGLWindow& rhs) { return _window_ptr==rhs._window_ptr; }
|
|
||||||
|
|
||||||
int getWindowAttribute(int) const;
|
|
||||||
inline GLFWwindow* getWindowPtr() const { return _window_ptr; }
|
|
||||||
inline const GLFWwindow* getObjectArena() const { return _arena; }
|
|
||||||
inline std::string getTitle() const { return _title; }
|
|
||||||
std::array<int, 2> getSize() const;
|
|
||||||
bool shouldClose() const;
|
|
||||||
inline void pollEvents() const { CheckForMainThread(); glfwPollEvents(); }
|
|
||||||
inline void swapBuffers() const { glfwSwapBuffers(_window_ptr); }
|
|
||||||
|
|
||||||
void setSize(unsigned int x, unsigned int y);
|
|
||||||
void setTitle(const std::string&);
|
|
||||||
void shouldClose(bool);
|
|
||||||
|
|
||||||
template<WindowCallbacks CallbackType, typename CallbackFunc>
|
|
||||||
void setCallback(CallbackFunc callback) {
|
|
||||||
CheckForMainThread();
|
|
||||||
auto tmp = makeCurrent();
|
|
||||||
static auto this_ptr = this;
|
|
||||||
static typename OGLWindowCallbacks<CallbackType>::type tmp_callback = callback;
|
|
||||||
if constexpr (CallbackType == KEY) {
|
|
||||||
glfwSetKeyCallback(_window_ptr, [](GLFWwindow*, int a, int b, int c, int d){
|
|
||||||
tmp_callback(this_ptr, a,b,c,d);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == CHAR) {
|
|
||||||
glfwSetCharCallback(_window_ptr, [](GLFWwindow*, int a) {
|
|
||||||
tmp_callback(this_ptr, a);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == CHAR_MODS) {
|
|
||||||
glfwSetCharModsCallback(_window_ptr, [](GLFWwindow*, unsigned int a, int b) {
|
|
||||||
tmp_callback(this_ptr, a, b);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == CURSOR_ENTER) {
|
|
||||||
glfwSetCursorEnterCallback(_window_ptr, [](GLFWwindow*, int a) {
|
|
||||||
tmp_callback(this_ptr, a);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == CURSOR_POS) {
|
|
||||||
glfwSetCursorPosCallback(_window_ptr, [](GLFWwindow*, double a, double b){
|
|
||||||
tmp_callback(this_ptr, a,b);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == MOUSE_BUTTON) {
|
|
||||||
glfwSetMouseButtonCallback(_window_ptr, [](GLFWwindow*, int a, int b, int c){
|
|
||||||
tmp_callback(this_ptr, a,b,c);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == SCROLL) {
|
|
||||||
glfwSetScrollCallback(_window_ptr, [](GLFWwindow*, double a, double b) {
|
|
||||||
tmp_callback(this_ptr, a,b);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == DROP) {
|
|
||||||
glfwSetDropCallback(_window_ptr, [](GLFWwindow*, int a, const char** b) {
|
|
||||||
tmp_callback(this_ptr, a, b);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_POS) {
|
|
||||||
glfwSetWindowPosCallback(_window_ptr, [](GLFWwindow*, int a, int b){
|
|
||||||
tmp_callback(this_ptr, a,b);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_SIZE) {
|
|
||||||
glfwSetWindowSizeCallback(_window_ptr, [](GLFWwindow*, int a, int b){
|
|
||||||
tmp_callback(this_ptr, a,b);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_CLOSE) {
|
|
||||||
glfwSetWindowCloseCallback(_window_ptr, [](GLFWwindow*){
|
|
||||||
tmp_callback(this_ptr);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_REFRESH) {
|
|
||||||
glfwSetWindowRefreshCallback(_window_ptr, [](GLFWwindow*){
|
|
||||||
tmp_callback(this_ptr);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_FOCUS) {
|
|
||||||
glfwSetWindowFocusCallback(_window_ptr, [](GLFWwindow*, int a) {
|
|
||||||
tmp_callback(this_ptr, a);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_ICONIFY) {
|
|
||||||
glfwSetWindowIconifyCallback(_window_ptr, [](GLFWwindow*, int a) {
|
|
||||||
tmp_callback(this_ptr, a);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_MAX) {
|
|
||||||
glfwSetWindowMaximizeCallback(_window_ptr, [](GLFWwindow*, int a) {
|
|
||||||
tmp_callback(this_ptr, a);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == FRAMEBUFFER_SIZE) {
|
|
||||||
glfwSetFramebufferSizeCallback(_window_ptr, [](GLFWwindow*, int a, int b) {
|
|
||||||
tmp_callback(this_ptr, a, b);
|
|
||||||
});
|
|
||||||
} else if constexpr (CallbackType == WINDOW_SCALE) {
|
|
||||||
glfwSetWindowContentScaleCallback(_window_ptr, [](GLFWwindow*, int a, int b) {
|
|
||||||
tmp_callback(this_ptr, a, b);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
static_assert(false, "No matching callback.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
};
|
|
||||||
#endif
|
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
#pragma once
|
||||||
|
#ifndef _NB_SHADER
|
||||||
|
#define _NB_SHADER
|
||||||
|
|
||||||
|
#include <GLLoad.h>
|
||||||
|
|
||||||
|
#include <cctype>
|
||||||
|
#include <cstring>
|
||||||
|
#include <exception>
|
||||||
|
#include <fstream>
|
||||||
|
#include <iostream>
|
||||||
|
#include <map>
|
||||||
|
#include <regex>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include <glm/glm.hpp>
|
||||||
|
#include <glm/gtc/matrix_transform.hpp>
|
||||||
|
#include <glm/gtc/type_ptr.hpp>
|
||||||
|
|
||||||
|
// #define _PREPROC_FUNC_PARAMS_ (const ShaderPreprocessor&, ShaderUnit&, unsigned int, const std::string&, std::vector<uint8_t>&)
|
||||||
|
|
||||||
|
namespace NB {
|
||||||
|
|
||||||
|
class ShaderPreprocessorError : public std::runtime_error {
|
||||||
|
public:
|
||||||
|
enum Codes : unsigned char {
|
||||||
|
NONE,
|
||||||
|
FILE_NOT_FOUND,
|
||||||
|
BUILTIN_NOT_FOUND,
|
||||||
|
CUSTOM,
|
||||||
|
UNDEFINED
|
||||||
|
};
|
||||||
|
|
||||||
|
const Codes code;
|
||||||
|
|
||||||
|
ShaderPreprocessorError(const std::string&, const std::string& file="", int line=-1);
|
||||||
|
ShaderPreprocessorError(Codes, const std::string& arg="", const std::string& file="", int line=-1);
|
||||||
|
|
||||||
|
protected:
|
||||||
|
static std::string errorCodeParser(Codes, const std::string& arg="");
|
||||||
|
};
|
||||||
|
|
||||||
|
class ShaderError : public std::runtime_error {
|
||||||
|
public:
|
||||||
|
ShaderError(const std::string&, const char* shad=nullptr, const std::string& file="", int line=-1);
|
||||||
|
|
||||||
|
protected:
|
||||||
|
std::string formatString(const std::string&, const char* shad=nullptr, const std::string& file="", int line=-1);
|
||||||
|
};
|
||||||
|
|
||||||
|
struct File {
|
||||||
|
// typedef std::tuple<std::string, std::string, std::string> FilePath;
|
||||||
|
struct FilePath {
|
||||||
|
std::string dir;
|
||||||
|
std::string basename;
|
||||||
|
std::string ext;
|
||||||
|
};
|
||||||
|
FilePath path;
|
||||||
|
std::stringstream src;
|
||||||
|
std::map<unsigned int, std::shared_ptr<File>> include_map;
|
||||||
|
|
||||||
|
File() {}
|
||||||
|
File(const File& rhs) { *this = rhs; }
|
||||||
|
|
||||||
|
File& operator=(const File& rhs) {
|
||||||
|
path = rhs.path;
|
||||||
|
src.str("");
|
||||||
|
src << rhs.src.rdbuf();
|
||||||
|
include_map = rhs.include_map;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// File::FilePath get_file_path(std::string);
|
||||||
|
|
||||||
|
class ShaderPreprocessor;
|
||||||
|
|
||||||
|
enum OpenGLProfiles {
|
||||||
|
Core,
|
||||||
|
Compatibility,
|
||||||
|
ES
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ShaderUnit {
|
||||||
|
GLenum type = 0x0;
|
||||||
|
File file;
|
||||||
|
std::string preprocSource;
|
||||||
|
std::map<std::string, std::string> defines;
|
||||||
|
short vMajor=0, vMinor=0;
|
||||||
|
OpenGLProfiles profile = Core;
|
||||||
|
};
|
||||||
|
|
||||||
|
class ShaderPreprocessor;
|
||||||
|
|
||||||
|
class ShaderProgram {
|
||||||
|
friend ShaderPreprocessor;
|
||||||
|
public:
|
||||||
|
ShaderProgram() {}
|
||||||
|
ShaderProgram(const ShaderProgram& rhs) = delete;
|
||||||
|
ShaderProgram(ShaderProgram&& rhs);
|
||||||
|
|
||||||
|
~ShaderProgram();
|
||||||
|
|
||||||
|
ShaderProgram& operator=(const ShaderProgram& rhs) = delete;
|
||||||
|
ShaderProgram& operator=(ShaderProgram&& rhs);
|
||||||
|
|
||||||
|
std::vector<ShaderUnit> getShaders() const;
|
||||||
|
ShaderUnit getShaders(unsigned int) const;
|
||||||
|
void use() const;
|
||||||
|
unsigned int id() const;
|
||||||
|
|
||||||
|
void setBool(const std::string& name, bool value) const;
|
||||||
|
void setInt(const std::string& name, int value) const;
|
||||||
|
void setUnsigned(const std::string& name, int value) const;
|
||||||
|
void setFloat(const std::string& name, float value) const;
|
||||||
|
void setMat4(const std::string& name, glm::mat4& value) const;
|
||||||
|
|
||||||
|
static ShaderProgram CreateShaderProgram(std::vector<ShaderUnit>&);
|
||||||
|
|
||||||
|
private:
|
||||||
|
ShaderProgram(std::vector<ShaderUnit>& shaders) : _shader_units(shaders){}
|
||||||
|
|
||||||
|
std::vector<ShaderUnit> _shader_units;
|
||||||
|
unsigned int _id;
|
||||||
|
};
|
||||||
|
|
||||||
|
class ShaderPreprocessor {
|
||||||
|
public:
|
||||||
|
typedef ShaderPreprocessorError::Codes Codes;
|
||||||
|
|
||||||
|
enum TokenType {
|
||||||
|
TK,
|
||||||
|
DR,
|
||||||
|
WS,
|
||||||
|
NL,
|
||||||
|
LC,
|
||||||
|
BC
|
||||||
|
};
|
||||||
|
static std::string TokenName(const TokenType&);
|
||||||
|
|
||||||
|
std::map<std::string, GLenum> AcceptedExtensions = {
|
||||||
|
{".frag", GL_FRAGMENT_SHADER},
|
||||||
|
{".fs", GL_FRAGMENT_SHADER},
|
||||||
|
{".vert", GL_VERTEX_SHADER},
|
||||||
|
{".vs", GL_VERTEX_SHADER},
|
||||||
|
{".tess", 0x0},
|
||||||
|
{".geom", GL_GEOMETRY_SHADER},
|
||||||
|
{".comp", 0x0},
|
||||||
|
{".shad", 0x0},
|
||||||
|
{".glsl", 0x0}
|
||||||
|
};
|
||||||
|
std::map<std::string, OpenGLProfiles> AcceptedProfiles {
|
||||||
|
{"core", Core},
|
||||||
|
{"compatibility", Compatibility},
|
||||||
|
{"es", ES}
|
||||||
|
};
|
||||||
|
std::vector<std::string> Directories;
|
||||||
|
std::map<std::string, std::string> BuiltIns;
|
||||||
|
|
||||||
|
ShaderPreprocessor();
|
||||||
|
|
||||||
|
|
||||||
|
File load(const std::string, bool builtin_first=false) const;
|
||||||
|
ShaderUnit& preprocess(const std::string&, ShaderUnit&) const;
|
||||||
|
ShaderUnit preprocess(File, GLenum shader_type=0x0) const;
|
||||||
|
ShaderUnit preprocess(const std::string&, GLenum shader_type=0x0) const;
|
||||||
|
ShaderProgram ReloadFromFile(const ShaderProgram& rhs) const;
|
||||||
|
ShaderProgram CreateShaderProgram(std::vector<std::string>) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
typedef std::pair<TokenType, std::string> Token;
|
||||||
|
typedef std::vector<std::string> StringVec;
|
||||||
|
|
||||||
|
inline bool directive_dispatch(ShaderUnit&, const std::string&) const;
|
||||||
|
inline std::vector<Token> tokenize(const std::string&) const;
|
||||||
|
|
||||||
|
inline bool preprocessor_include(ShaderUnit&, const StringVec&, const std::string&) const;
|
||||||
|
inline bool preprocessor_version(ShaderUnit&, const StringVec&, const std::string&) const;
|
||||||
|
inline bool preprocessor_define(ShaderUnit&, const StringVec&, const std::string&) const;
|
||||||
|
// inline bool preprocessor_uniform(ShaderUnit&, const std::string&, const std::string&) const;
|
||||||
|
|
||||||
|
File loadFromBase(const std::string, const std::string base="") const;
|
||||||
|
File loadFromDirectories(const std::string) const;
|
||||||
|
File loadFromBuiltIn(const std::string) const;
|
||||||
|
File load_BuiltInFirst(const std::string) const;
|
||||||
|
File load_FilesFirst(const std::string) const;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -1,118 +1,5 @@
|
|||||||
#include <NBGraphics/Buffers.hpp>
|
#include "Buffers.hpp"
|
||||||
|
|
||||||
namespace nb {
|
namespace nb {
|
||||||
|
|
||||||
const ConstantMap<GLenum, std::string> BufferTypes({
|
|
||||||
{GL_ARRAY_BUFFER, "GL_ARRAY_BUFFER"},
|
|
||||||
{GL_ELEMENT_ARRAY_BUFFER, "GL_ELEMENT_BUFFER"}
|
|
||||||
});
|
|
||||||
|
|
||||||
using BufferErrorCodes = BufferError::Codes;
|
|
||||||
const std::string BufferError::type = "nb::BufferError";
|
|
||||||
const ErrorCodeMap BufferError::ErrorMessages = {
|
|
||||||
{ BufferErrorCodes::UNDEFINED, "Error" },
|
|
||||||
{ BufferErrorCodes::DATA_OVERFLOW, "Attempting buffer overflow" },
|
|
||||||
{ BufferErrorCodes::DATA_ERROR, "Invalid memory operation" },
|
|
||||||
{ BufferErrorCodes::BAD_DATA_TYPE, "Entered data type not allowed for buffer type"}
|
|
||||||
};
|
|
||||||
|
|
||||||
// class Buffer
|
|
||||||
|
|
||||||
Buffer::Buffer(GLenum target_) : OpenGLObject(), Target(target_) {
|
|
||||||
declare();
|
|
||||||
}
|
|
||||||
|
|
||||||
Buffer::Buffer(GLenum target_, const ByteVector& data_, GLenum usage_) : Buffer(target_) {
|
|
||||||
bind();
|
|
||||||
data(data_, usage_);
|
|
||||||
}
|
|
||||||
|
|
||||||
Buffer::Buffer(Buffer&& rval) : Target(rval.Target) {
|
|
||||||
*this = std::move(rval);
|
|
||||||
}
|
|
||||||
|
|
||||||
Buffer& Buffer::operator=(Buffer&& rhs) {
|
|
||||||
if (Target != rhs.Target) {
|
|
||||||
auto targ_name = BufferTypes[Target];
|
|
||||||
THROW(OpenGLObjectError(
|
|
||||||
OpenGLObjectError::Codes::INVALID_OBJECT,
|
|
||||||
"w/ BufferType "+targ_name+" != BufferType "+BufferTypes[Target]
|
|
||||||
));
|
|
||||||
}
|
|
||||||
OpenGLObject::operator=(std::move(rhs));
|
|
||||||
_usage = rhs._usage;
|
|
||||||
_size = rhs._size;
|
|
||||||
|
|
||||||
rhs._usage = GL_STATIC_DRAW;
|
|
||||||
rhs._size = 0;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
GLenum Buffer::usage() const { return _usage; }
|
|
||||||
|
|
||||||
size_t Buffer::size() const { return _size; }
|
|
||||||
|
|
||||||
ByteVector Buffer::data() const {
|
|
||||||
bind();
|
|
||||||
ByteVector ret(_size);
|
|
||||||
OPENGL_CALL(glGetBufferSubData(Target, 0, _size, ret.data()));
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Buffer::data(const void* data_, size_t size_, GLenum usage_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(glBufferData(Target, size_, data_, usage_));
|
|
||||||
_size = size_;
|
|
||||||
_usage = usage_;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Buffer::data(const ByteVector& data_, GLenum usage_) {
|
|
||||||
declare();
|
|
||||||
data(data_.data(), data_.size(), usage_);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Buffer::subdata(const void* data_, size_t size_, GLintptr offset_) {
|
|
||||||
bind();
|
|
||||||
if (offset_+size_ <= _size) {
|
|
||||||
THROW(BufferError(BufferError::Codes::DATA_OVERFLOW));
|
|
||||||
}
|
|
||||||
OPENGL_CALL(glBufferSubData(Target, offset_, size_, data_));
|
|
||||||
}
|
|
||||||
|
|
||||||
void Buffer::subdata(const ByteVector& data_, GLintptr offset_) {
|
|
||||||
bind();
|
|
||||||
size_t size_ = data_.size();
|
|
||||||
subdata(data_.data(), size_);
|
|
||||||
}
|
|
||||||
|
|
||||||
// class UniformBuffer
|
|
||||||
UniformBuffer::UniformBuffer() : Buffer(GL_UNIFORM_BUFFER) {}
|
|
||||||
|
|
||||||
void UniformBuffer::bind() const {
|
|
||||||
Buffer::bind();
|
|
||||||
OPENGL_CALL(glBindBufferBase(GL_UNIFORM_BUFFER, _index, id()));
|
|
||||||
}
|
|
||||||
|
|
||||||
GLuint UniformBuffer::bufferIndex() const { return _index; }
|
|
||||||
|
|
||||||
GLuint UniformBuffer::bufferIndex(GLuint idx) {
|
|
||||||
return (_index = idx);
|
|
||||||
}
|
|
||||||
|
|
||||||
// class ElementBuffer
|
|
||||||
|
|
||||||
template void ElementBuffer::data<uint8_t>(const std::vector<uint8_t>& data, GLenum usage);
|
|
||||||
template void ElementBuffer::data<uint16_t>(const std::vector<uint16_t>& data, GLenum usage);
|
|
||||||
template void ElementBuffer::data<uint32_t>(const std::vector<uint32_t>& data, GLenum usage);
|
|
||||||
template void ElementBuffer::data<uint8_t>(const uint8_t* const data, size_t size, GLenum usage);
|
|
||||||
template void ElementBuffer::data<uint16_t>(const uint16_t* const data, size_t size, GLenum usage);
|
|
||||||
template void ElementBuffer::data<uint32_t>(const uint32_t* const data, size_t size, GLenum usage);
|
|
||||||
|
|
||||||
template void ElementBuffer::subdata<uint8_t>(const uint8_t* const data, size_t size, GLintptr offset=0);
|
|
||||||
template void ElementBuffer::subdata<uint16_t>(const uint16_t* const data, size_t size, GLintptr offset=0);
|
|
||||||
template void ElementBuffer::subdata<uint32_t>(const uint32_t* const data, size_t size, GLintptr offset=0);
|
|
||||||
template void ElementBuffer::subdata<uint8_t>(const std::vector<uint8_t>& data, GLintptr offset=0);
|
|
||||||
template void ElementBuffer::subdata<uint16_t>(const std::vector<uint16_t>& data, GLintptr offset=0);
|
|
||||||
template void ElementBuffer::subdata<uint32_t>(const std::vector<uint32_t>& data, GLintptr offset=0);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
#include <NBGraphics/Camera.hpp>
|
#include "Camera.h"
|
||||||
|
namespace NB {
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
// Camera class
|
// Camera class
|
||||||
Camera::Camera(const Vec3& pos, const Vec3& tar, const Vec3& up) {
|
Camera::Camera(const Vec3& pos, const Vec3& tar, const Vec3& up) {
|
||||||
|
|||||||
@@ -0,0 +1,307 @@
|
|||||||
|
#include "Draw.h"
|
||||||
|
|
||||||
|
namespace NB{
|
||||||
|
|
||||||
|
DrawError::DrawError(
|
||||||
|
const std::string& msg,
|
||||||
|
const std::string& file,
|
||||||
|
int line) : std::runtime_error(NB::formatDebugString(msg, file, line)) {}
|
||||||
|
|
||||||
|
uint8_t VerticesFromPrimitives(GLenum type, unsigned int num_prims) {
|
||||||
|
switch(type) {
|
||||||
|
case GL_POINTS:
|
||||||
|
return num_prims;
|
||||||
|
case GL_LINES:
|
||||||
|
return num_prims*2;
|
||||||
|
break;
|
||||||
|
case GL_LINE_STRIP:
|
||||||
|
return num_prims+1;
|
||||||
|
break;
|
||||||
|
case GL_LINE_LOOP:
|
||||||
|
return num_prims;
|
||||||
|
break;
|
||||||
|
case GL_TRIANGLES:
|
||||||
|
return num_prims*3;
|
||||||
|
break;
|
||||||
|
case GL_TRIANGLE_STRIP:
|
||||||
|
case GL_TRIANGLE_FAN:
|
||||||
|
return num_prims+2;
|
||||||
|
break;
|
||||||
|
case GL_QUADS:
|
||||||
|
return 4*num_prims;
|
||||||
|
break;
|
||||||
|
case GL_QUAD_STRIP:
|
||||||
|
return 2*num_prims+2;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return num_prims;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t PrimitivesFromVertices(GLenum type, unsigned int num_verts) {
|
||||||
|
switch(type) {
|
||||||
|
case GL_POINTS:
|
||||||
|
return num_verts;
|
||||||
|
case GL_LINES:
|
||||||
|
return num_verts/2;
|
||||||
|
break;
|
||||||
|
case GL_LINE_STRIP:
|
||||||
|
return num_verts-1;
|
||||||
|
break;
|
||||||
|
case GL_LINE_LOOP:
|
||||||
|
return num_verts;
|
||||||
|
break;
|
||||||
|
case GL_TRIANGLES:
|
||||||
|
return num_verts/3;
|
||||||
|
break;
|
||||||
|
case GL_TRIANGLE_STRIP:
|
||||||
|
case GL_TRIANGLE_FAN:
|
||||||
|
return num_verts-2;
|
||||||
|
break;
|
||||||
|
case GL_QUADS:
|
||||||
|
return num_verts/4;
|
||||||
|
break;
|
||||||
|
case GL_QUAD_STRIP:
|
||||||
|
return num_verts/2 - 1;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return num_verts;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// DrawBuffer class
|
||||||
|
DrawBuffer::DrawBuffer(VertexAttributeList vas, GLenum prim_type)
|
||||||
|
: _gl_primitive_type(prim_type), _VAO() {
|
||||||
|
_vert_data = std::make_shared<Buffer>(GL_ARRAY_BUFFER);
|
||||||
|
_elmt_data = std::make_shared<Buffer>(GL_ELEMENT_ARRAY_BUFFER);
|
||||||
|
_VAO.addVBO(_vert_data);
|
||||||
|
_VAO.changeEBO(_elmt_data);
|
||||||
|
try {
|
||||||
|
throw _VAO.checkValid(vas);
|
||||||
|
} catch (VAOError vaoe) {
|
||||||
|
if (vaoe.error) {
|
||||||
|
_VAO.addVertexAttributes(DrawBuffer::defaultVAO(vas));
|
||||||
|
} else {
|
||||||
|
_VAO.addVertexAttributes(vas);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList DrawBuffer::defaultVAO(VertexAttributeList vert_attrs) {
|
||||||
|
GLuint vert_id = _vert_data->id();
|
||||||
|
unsigned int vert_size = 0;
|
||||||
|
for (const VertexAttribute& va : vert_attrs) {
|
||||||
|
vert_size += va.GLSLSize * GLSLTypeSize(va.GLSLType);
|
||||||
|
}
|
||||||
|
unsigned int curr_byte = 0;
|
||||||
|
for (VertexAttribute& va : vert_attrs) {
|
||||||
|
va.ptr.buffer = vert_id;
|
||||||
|
va.ptr.stride = vert_size;
|
||||||
|
va.ptr.offset = curr_byte;
|
||||||
|
va.ptr.divisor = 0;
|
||||||
|
curr_byte += va.GLSLSize * GLSLTypeSize(va.GLSLType);
|
||||||
|
}
|
||||||
|
return vert_attrs;
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList DrawBuffer::changeVertLayout(unsigned int i, VertexAttributePointer vap) {
|
||||||
|
GLuint vert_id = _vert_data->id();
|
||||||
|
vap.buffer = (vap.buffer) ? vap.buffer : vert_id;
|
||||||
|
VertexAttributeList vas = _VAO.getLayout();
|
||||||
|
unsigned int idx = 0;
|
||||||
|
for (const VertexAttribute& va : vas) {
|
||||||
|
if (va.ptr.buffer == vert_id) {
|
||||||
|
if (idx == i) {
|
||||||
|
return _VAO.changeLayout(i, vap);
|
||||||
|
}
|
||||||
|
idx++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
THROW_DRAW_ERROR("Could not find vertex attribute with index " + std::to_string(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int DrawBuffer::vertSize() const { return _VAO.vertSize(_vert_data->id()); }
|
||||||
|
|
||||||
|
void DrawBuffer::draw() const {
|
||||||
|
_VAO.bind();
|
||||||
|
glDrawElements(_gl_primitive_type, _elmt_data->size() / GLSLTypeSize(GL_INT), GL_UNSIGNED_INT, 0);
|
||||||
|
_VAO.unbind();
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int DrawBuffer::elementBufferID() const { return _elmt_data->id(); }
|
||||||
|
|
||||||
|
unsigned int DrawBuffer::vertexBufferID() const { return _vert_data->id(); }
|
||||||
|
|
||||||
|
RawVec DrawBuffer::vertAttrData(unsigned int i) {
|
||||||
|
if (!_vert_data->isInitialized()) {
|
||||||
|
throw DrawError("Vertex buffer is not initialized.");
|
||||||
|
}
|
||||||
|
return _VAO.attributeData(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
RawVec DrawBuffer::vertAttrData(unsigned int i, const RawVec& newdata) {
|
||||||
|
if (!(_vert_data->isInitialized())) {
|
||||||
|
VertexAttribute va = _VAO.getLayout()[i];
|
||||||
|
vertexData(newdata.size() / (va.GLSLSize*GLSLTypeSize(va.GLSLType)));
|
||||||
|
std::cout << "From DrawBuffer::vertAttrData(int, RawVec) - vert buf size: " << _vert_data->size() << "\n";
|
||||||
|
}
|
||||||
|
return _VAO.attributeData(i, newdata);
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawBuffer::elementData(unsigned int num_prims) {
|
||||||
|
elementData(std::vector<unsigned int>(VerticesFromPrimitives(_gl_primitive_type, num_prims)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawBuffer::elementData(const std::vector<unsigned int>& elements) {
|
||||||
|
_num_prims = PrimitivesFromVertices(_gl_primitive_type, elements.size());
|
||||||
|
_elmt_data->data(vectorToRaw(elements));
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawBuffer::elementData(const std::vector<unsigned int>& elements, unsigned int offset) {
|
||||||
|
_VAO.bind();
|
||||||
|
if (!_elmt_data->isInitialized()) {
|
||||||
|
std::vector<unsigned int> init_elmts(elements);
|
||||||
|
init_elmts.insert(init_elmts.cbegin(), offset, 0);
|
||||||
|
elementData(init_elmts, 0);
|
||||||
|
} else {
|
||||||
|
_elmt_data->data(vectorToRaw(elements), offset);
|
||||||
|
}
|
||||||
|
_VAO.unbind();
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawBuffer::vertexData(unsigned int num_verts) {
|
||||||
|
vertexData(RawVec(num_verts * vertSize()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawBuffer::vertexData(const RawVec& vert_data) {
|
||||||
|
// Check for uninitialized Vertex Pointers. If so, will fallback to default VAO setup.
|
||||||
|
// Otherwise, set VAO to provided Vertex Atributes.
|
||||||
|
int vert_size = vertSize();
|
||||||
|
if (vert_data.size() % vert_size != 0) {
|
||||||
|
THROW_DRAW_ERROR("Initializing data does not match vertex size of " + std::to_string(vert_size) + ".");
|
||||||
|
}
|
||||||
|
_num_verts = vert_data.size() / vert_size;
|
||||||
|
// TODO: Make it not static draw all the time
|
||||||
|
|
||||||
|
_VAO.bind();
|
||||||
|
_vert_data->data(vert_data);
|
||||||
|
_VAO.unbind();
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawBuffer::vertexData(const RawVec& data, unsigned int offset) {
|
||||||
|
_VAO.bind();
|
||||||
|
if (!_vert_data->isInitialized()) {
|
||||||
|
RawVec load_data(offset);
|
||||||
|
load_data.insert(load_data.end(), data.begin(), data.end());
|
||||||
|
vertexData(load_data, 0);
|
||||||
|
} else {
|
||||||
|
try{
|
||||||
|
_vert_data->data(data, offset);
|
||||||
|
} catch(BufferError& e) {
|
||||||
|
THROW_DRAW_ERROR("NB::BufferError in loadVBO:\n\t" + std::string(e.what()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_VAO.unbind();
|
||||||
|
}
|
||||||
|
|
||||||
|
// DrawInstanceBufferClass
|
||||||
|
DrawInstanceBuffer::DrawInstanceBuffer(
|
||||||
|
VertexAttributeList vert_vas,
|
||||||
|
VertexAttributeList inst_vas,
|
||||||
|
GLenum prim_type
|
||||||
|
): DrawBuffer(vert_vas, prim_type) {
|
||||||
|
_inst_data = std::make_shared<Buffer>(GL_ARRAY_BUFFER);
|
||||||
|
_VAO.addVBO(_inst_data);
|
||||||
|
try {
|
||||||
|
throw _VAO.checkValid(inst_vas);
|
||||||
|
} catch (VAOError vaoe) {
|
||||||
|
if (vaoe.error) {
|
||||||
|
_VAO.addVertexAttributes(defaultVAO(inst_vas));
|
||||||
|
} else {
|
||||||
|
_VAO.addVertexAttributes(inst_vas);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int DrawInstanceBuffer::instSize() const { return _VAO.vertSize(_inst_data->id()); }
|
||||||
|
|
||||||
|
unsigned int DrawInstanceBuffer::instanceBufferID() const { return _inst_data->id(); }
|
||||||
|
|
||||||
|
void DrawInstanceBuffer::instanceData(unsigned int num_inst) {
|
||||||
|
instanceData(RawVec(instSize() * num_inst));
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawInstanceBuffer::instanceData(const RawVec& inst_data) {
|
||||||
|
int inst_size = instSize();
|
||||||
|
if (inst_data.size() % inst_size != 0) {
|
||||||
|
THROW_DRAW_ERROR("Initializing data does not match instance size of " + std::to_string(inst_size) + ".");
|
||||||
|
}
|
||||||
|
_num_inst = inst_data.size() / inst_size;
|
||||||
|
|
||||||
|
_VAO.bind();
|
||||||
|
_inst_data->data(inst_data);
|
||||||
|
_VAO.unbind();
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawInstanceBuffer::instanceData(const RawVec& data, unsigned int offset) {
|
||||||
|
_VAO.bind();
|
||||||
|
if (!_inst_data->isInitialized()) {
|
||||||
|
RawVec load_data(offset);
|
||||||
|
load_data.insert(load_data.end(), data.begin(), data.end());
|
||||||
|
instanceData(load_data, 0);
|
||||||
|
} else {
|
||||||
|
try{
|
||||||
|
_inst_data->data(data, offset);
|
||||||
|
} catch(BufferError& e) {
|
||||||
|
THROW_DRAW_ERROR("NB::BufferError in loadIBO:\n\t" + std::string(e.what()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_VAO.unbind();
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList DrawInstanceBuffer::defaultVAO(VertexAttributeList inst_attrs) {
|
||||||
|
GLuint inst_id = _inst_data->id();
|
||||||
|
unsigned int vert_size = 0;
|
||||||
|
for (const VertexAttribute& va : inst_attrs) {
|
||||||
|
vert_size += va.GLSLSize * GLSLTypeSize(va.GLSLType);
|
||||||
|
}
|
||||||
|
unsigned int curr_byte = 0;
|
||||||
|
for (VertexAttribute& va : inst_attrs) {
|
||||||
|
va.ptr.buffer = inst_id;
|
||||||
|
va.ptr.stride = vert_size;
|
||||||
|
va.ptr.offset = curr_byte;
|
||||||
|
va.ptr.divisor = 1;
|
||||||
|
curr_byte += va.GLSLSize * GLSLTypeSize(va.GLSLType);
|
||||||
|
}
|
||||||
|
return inst_attrs;
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList DrawInstanceBuffer::changeInstanceLayout(unsigned int i, VertexAttributePointer vap) {
|
||||||
|
GLuint inst_id = _inst_data->id();
|
||||||
|
vap.buffer = (vap.buffer) ? vap.buffer : inst_id;
|
||||||
|
VertexAttributeList vas = _VAO.getLayout();
|
||||||
|
unsigned int vas_size = vas.size();
|
||||||
|
unsigned int inst_idx = 0;
|
||||||
|
unsigned int idx = 0;
|
||||||
|
for (const VertexAttribute& va : vas) {
|
||||||
|
if (va.ptr.buffer == inst_id) {
|
||||||
|
if (inst_idx == i) {
|
||||||
|
return _VAO.changeLayout(idx, vap);
|
||||||
|
}
|
||||||
|
inst_idx++;
|
||||||
|
}
|
||||||
|
idx++;
|
||||||
|
}
|
||||||
|
THROW_DRAW_ERROR("Could not find instance attribute with index " + std::to_string(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawInstanceBuffer::draw() const {
|
||||||
|
_VAO.bind();
|
||||||
|
glDrawElementsInstanced(_gl_primitive_type, _elmt_data->size() / GLSLTypeSize(GL_UNSIGNED_INT), GL_UNSIGNED_INT, (void*)_elmt_data->id(), _num_inst);
|
||||||
|
_VAO.unbind();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,401 +0,0 @@
|
|||||||
#include <NBGraphics/FrameBuffers.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
using FBOErrorCodes = FrameBufferError::Codes;
|
|
||||||
const std::string FrameBufferError::type = "nb::FrameBufferError";
|
|
||||||
const ErrorCodeMap FrameBufferError::ErrorMessages = {
|
|
||||||
{FBOErrorCodes::UNDEFINED, "Error"},
|
|
||||||
{FBOErrorCodes::INVALID_VALUE, "Invalid value"}
|
|
||||||
};
|
|
||||||
|
|
||||||
GLuint FrameBufferBase::declare() {
|
|
||||||
if (!_id) {
|
|
||||||
OPENGL_CALL(
|
|
||||||
glGenFramebuffers(1, &_id)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
bind();
|
|
||||||
return _id;
|
|
||||||
}
|
|
||||||
|
|
||||||
void FrameBufferBase::remove() {
|
|
||||||
if (_id) {
|
|
||||||
unbind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glDeleteFramebuffers(1, &_id)
|
|
||||||
);
|
|
||||||
_id=0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
FrameBufferBase::FrameBufferBase(GLenum target) : Target(target) {}
|
|
||||||
|
|
||||||
std::shared_ptr<RenderTarget> FrameBufferBase::detach(GLenum attch_) {
|
|
||||||
bind();
|
|
||||||
auto ret = _attachments.at(attch_);
|
|
||||||
_attachments.erase(attch_);
|
|
||||||
OPENGL_CALL(
|
|
||||||
glFramebufferTexture(Target, attch_, 0, 0)
|
|
||||||
);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
void FrameBufferBase::attach(
|
|
||||||
GLenum attachment_,
|
|
||||||
std::shared_ptr<Texture> texture_,
|
|
||||||
unsigned int level_,
|
|
||||||
unsigned int layer_
|
|
||||||
) {
|
|
||||||
declare();
|
|
||||||
if (attachment_ == GL_NONE) {
|
|
||||||
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
|
|
||||||
"Cannot attach object to `GL_NONE`"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
OPENGL_CALL(glFramebufferTextureLayer(
|
|
||||||
Target,
|
|
||||||
attachment_,
|
|
||||||
texture_->id(),
|
|
||||||
level_,
|
|
||||||
layer_
|
|
||||||
));
|
|
||||||
_attachments[attachment_] = texture_;
|
|
||||||
}
|
|
||||||
|
|
||||||
void FrameBufferBase::attach(
|
|
||||||
GLenum attachment_,
|
|
||||||
std::shared_ptr<Texture> texture_,
|
|
||||||
unsigned int level_
|
|
||||||
) {
|
|
||||||
declare();
|
|
||||||
if (attachment_ == GL_NONE) {
|
|
||||||
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
|
|
||||||
"Cannot attach object to `GL_NONE`"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if (texTypeIs2D(texture_->Target)) {
|
|
||||||
OPENGL_CALL(glFramebufferTexture2D(
|
|
||||||
Target,
|
|
||||||
attachment_,
|
|
||||||
texture_->Target,
|
|
||||||
texture_->id(),
|
|
||||||
level_
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
OPENGL_CALL(glFramebufferTexture1D(
|
|
||||||
Target,
|
|
||||||
attachment_,
|
|
||||||
texture_->Target,
|
|
||||||
texture_->id(),
|
|
||||||
level_
|
|
||||||
));
|
|
||||||
}
|
|
||||||
_attachments[attachment_] = texture_;
|
|
||||||
}
|
|
||||||
|
|
||||||
void FrameBufferBase::attach(
|
|
||||||
GLenum attachment,
|
|
||||||
std::shared_ptr<RenderBuffer> renderbuffer
|
|
||||||
) {
|
|
||||||
declare();
|
|
||||||
if (attachment == GL_NONE) {
|
|
||||||
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
|
|
||||||
"Cannot attach RenderBuffer to `GL_NONE`"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
OPENGL_CALL(glFramebufferRenderbuffer(
|
|
||||||
Target,
|
|
||||||
attachment,
|
|
||||||
GL_RENDERBUFFER,
|
|
||||||
renderbuffer->id()
|
|
||||||
));
|
|
||||||
_attachments[attachment] = renderbuffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
void FrameBufferBase::bind() const {
|
|
||||||
if (_id) {
|
|
||||||
OPENGL_CALL(
|
|
||||||
glBindFramebuffer(Target, _id)
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
THROW(OpenGLObjectError(
|
|
||||||
OpenGLObjectError::Codes::INVALID_OBJECT,
|
|
||||||
"w/ FrameBuffer"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void FrameBufferBase::unbind() const {
|
|
||||||
OPENGL_CALL(
|
|
||||||
glBindFramebuffer(Target, 0)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
GLenum FrameBufferBase::status() const {
|
|
||||||
bind();
|
|
||||||
return OPENGL_CALL(
|
|
||||||
glCheckFramebufferStatus(Target)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool FrameBufferBase::complete() const {
|
|
||||||
return status() == GL_FRAMEBUFFER_COMPLETE;
|
|
||||||
}
|
|
||||||
|
|
||||||
FrameBufferBase::AttachmentMap FrameBufferBase::getAllBuffers() const {
|
|
||||||
return _attachments;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::shared_ptr<RenderTarget> FrameBufferBase::getBuffer(GLenum attch_) const {
|
|
||||||
try {
|
|
||||||
return _attachments.at(attch_);
|
|
||||||
} catch (const std::out_of_range& e) {
|
|
||||||
THROW(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// class ReadFrameBuffer
|
|
||||||
|
|
||||||
ReadFrameBuffer::ReadFrameBuffer()
|
|
||||||
: _location(GL_NONE), FrameBufferBase(GL_READ_FRAMEBUFFER) {}
|
|
||||||
|
|
||||||
ReadFrameBuffer& ReadFrameBuffer::operator=(WriteFrameBuffer&& mv) {
|
|
||||||
if (mv.id()) {
|
|
||||||
_attachments = mv.getAllBuffers();
|
|
||||||
mv.setWriteBuffer(GL_NONE);
|
|
||||||
mv._attachments = {};
|
|
||||||
mv._locations = {};
|
|
||||||
FrameBufferBase::OpenGLObject::operator=(std::move(mv));
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
ReadFrameBuffer& ReadFrameBuffer::operator=(ReadFrameBuffer&& mv) {
|
|
||||||
if (mv.id()) {
|
|
||||||
_attachments = mv._attachments;
|
|
||||||
_location = mv._location;
|
|
||||||
mv._attachments = {};
|
|
||||||
mv._location = GL_NONE;
|
|
||||||
FrameBufferBase::OpenGLObject::operator=(std::move(mv));
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::shared_ptr<RenderTarget> ReadFrameBuffer::getReadBuffer() const {
|
|
||||||
if (_location == GL_NONE) { return nullptr; }
|
|
||||||
return getBuffer(_location);
|
|
||||||
}
|
|
||||||
|
|
||||||
GLenum ReadFrameBuffer::getReadLocation() const { return _location; }
|
|
||||||
|
|
||||||
std::shared_ptr<RenderTarget> ReadFrameBuffer::setReadBuffer(GLenum attch_) {
|
|
||||||
bind();
|
|
||||||
if (attch_!=GL_NONE) {
|
|
||||||
try {
|
|
||||||
const auto& x = _attachments.at(attch_);
|
|
||||||
} catch (const std::out_of_range& e) {
|
|
||||||
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
|
|
||||||
"No buffer set at attachment"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_location = attch_;
|
|
||||||
OPENGL_CALL(glReadBuffer(_location));
|
|
||||||
return getReadBuffer();
|
|
||||||
}
|
|
||||||
|
|
||||||
// class WriteFrameBuffer
|
|
||||||
|
|
||||||
WriteFrameBuffer::WriteFrameBuffer()
|
|
||||||
: FrameBufferBase(GL_DRAW_FRAMEBUFFER) {}
|
|
||||||
|
|
||||||
WriteFrameBuffer& WriteFrameBuffer::operator=(ReadFrameBuffer&& rhs) {
|
|
||||||
if (rhs.id()) {
|
|
||||||
_attachments = rhs._attachments;
|
|
||||||
rhs.setReadBuffer(GL_NONE);
|
|
||||||
rhs._attachments = {};
|
|
||||||
rhs._location = GL_NONE;
|
|
||||||
FrameBufferBase::OpenGLObject::operator=(std::move(rhs));
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
WriteFrameBuffer& WriteFrameBuffer::operator=(WriteFrameBuffer&& rhs) {
|
|
||||||
if (rhs.id()) {
|
|
||||||
_attachments = rhs._attachments;
|
|
||||||
_locations = rhs._locations;
|
|
||||||
rhs._attachments = {};
|
|
||||||
rhs._locations = {};
|
|
||||||
FrameBufferBase::OpenGLObject::operator=(std::move(rhs));
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
using fRGBA = RGBA<float>;
|
|
||||||
|
|
||||||
std::vector<std::shared_ptr<Texture>> WriteFrameBuffer::getWriteBuffers() const {
|
|
||||||
const size_t count = _locations.size();
|
|
||||||
std::vector<std::shared_ptr<Texture>> ret(count);
|
|
||||||
for (int i = 0; i < count; ++i) {
|
|
||||||
ret[i] = std::static_pointer_cast<Texture>(getBuffer(_locations[i]));
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<GLenum> WriteFrameBuffer::getWriteLocations() const {
|
|
||||||
return _locations;
|
|
||||||
}
|
|
||||||
|
|
||||||
WriteFrameBuffer::DrawTexVec WriteFrameBuffer::setWriteBuffers(const std::vector<GLenum>& attchs_) {
|
|
||||||
bind();
|
|
||||||
for (GLenum loc : attchs_) {
|
|
||||||
if (getBuffer(loc)->Target == GL_RENDERBUFFER) {
|
|
||||||
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
|
|
||||||
"Cannot write to renderbuffer [ @ Attachment = "+std::to_string(loc)+" ]"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_locations = attchs_;
|
|
||||||
OPENGL_CALL(
|
|
||||||
glDrawBuffers(_locations.size(), _locations.data())
|
|
||||||
);
|
|
||||||
return getWriteBuffers();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::shared_ptr<Texture> WriteFrameBuffer::setWriteBuffer(GLenum attch_) {
|
|
||||||
bind();
|
|
||||||
if (attch_ == GL_NONE) {
|
|
||||||
std::vector<GLenum> tmp(_locations.size(), GL_NONE);
|
|
||||||
OPENGL_CALL(
|
|
||||||
glDrawBuffers(tmp.size(), tmp.data())
|
|
||||||
);
|
|
||||||
_locations = {};
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
setWriteBuffers({attch_});
|
|
||||||
return std::static_pointer_cast<Texture>(getBuffer(attch_));
|
|
||||||
}
|
|
||||||
|
|
||||||
fRGBA WriteFrameBuffer::clearColorValue() const {
|
|
||||||
bind();
|
|
||||||
float rgba[4];
|
|
||||||
OPENGL_CALL(
|
|
||||||
glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba)
|
|
||||||
);
|
|
||||||
return fRGBA{rgba[0], rgba[1], rgba[2], rgba[3]};
|
|
||||||
}
|
|
||||||
|
|
||||||
fRGBA WriteFrameBuffer::clearColorValue(const fRGBA& color) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glClearColor(color.r, color.g, color.b, color.a)
|
|
||||||
);
|
|
||||||
return color;
|
|
||||||
}
|
|
||||||
|
|
||||||
fRGBA WriteFrameBuffer::clearColorValue(float r, float g, float b, float a) {
|
|
||||||
return clearColorValue({r, g,b , a});
|
|
||||||
}
|
|
||||||
|
|
||||||
double WriteFrameBuffer::clearDepthValue() const {
|
|
||||||
bind();
|
|
||||||
double ret;
|
|
||||||
OPENGL_CALL(
|
|
||||||
glGetDoublev(GL_DEPTH_CLEAR_VALUE, &ret)
|
|
||||||
);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
double WriteFrameBuffer::clearDepthValue(double d_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glClearDepth(d_)
|
|
||||||
);
|
|
||||||
return d_;
|
|
||||||
}
|
|
||||||
|
|
||||||
GLint WriteFrameBuffer::clearStencilValue() const {
|
|
||||||
bind();
|
|
||||||
GLint ret;
|
|
||||||
OPENGL_CALL(
|
|
||||||
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &ret)
|
|
||||||
);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
GLint WriteFrameBuffer::clearStencilValue(GLint s_) {
|
|
||||||
declare();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glClearStencil(s_)
|
|
||||||
);
|
|
||||||
return s_;
|
|
||||||
}
|
|
||||||
|
|
||||||
void WriteFrameBuffer::clear(GLbitfield mask_) const {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glClear(mask_)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void WriteFrameBuffer::clearDepth() const {
|
|
||||||
clear(GL_DEPTH_BUFFER_BIT);
|
|
||||||
}
|
|
||||||
|
|
||||||
void WriteFrameBuffer::clearDepth(float val_) const {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glClearBufferfv(GL_DEPTH, 0, &val_)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void WriteFrameBuffer::clearStencil() const {
|
|
||||||
clear(GL_STENCIL_BUFFER_BIT);
|
|
||||||
}
|
|
||||||
|
|
||||||
void WriteFrameBuffer::clearStencil(GLint val_) const {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glClearBufferiv(GL_STENCIL, 0, &val_)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void WriteFrameBuffer::clearDepthStencil() const {
|
|
||||||
clear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
|
|
||||||
}
|
|
||||||
|
|
||||||
void WriteFrameBuffer::clearDepthStencil(float d_, GLint s_) const {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glClearBufferfi(GL_DEPTH_STENCIL, 0, d_, s_)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
FrameBuffer::FrameBuffer()
|
|
||||||
: FrameBufferBase(GL_FRAMEBUFFER) {}
|
|
||||||
|
|
||||||
FrameBuffer& FrameBuffer::operator=(FrameBuffer&& rhs) {
|
|
||||||
if (rhs.id()) {
|
|
||||||
_attachments = rhs._attachments;
|
|
||||||
_location = rhs._location;
|
|
||||||
_locations = rhs._locations;
|
|
||||||
rhs._attachments = {};
|
|
||||||
rhs._locations = {};
|
|
||||||
rhs._location = GL_NONE;
|
|
||||||
OpenGLObject::operator=(std::move(rhs));
|
|
||||||
}
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
FrameBuffer& FrameBuffer::operator=(ReadFrameBuffer&& rhs) {
|
|
||||||
ReadFrameBuffer::operator=(std::move(rhs));
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
FrameBuffer& FrameBuffer::operator=(WriteFrameBuffer&& rhs) {
|
|
||||||
WriteFrameBuffer::operator=(std::move(rhs));
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
#include <NBGraphics/Image.hpp>
|
|
||||||
|
|
||||||
using ImageErrorCodes = nb::ImageError::Codes;
|
|
||||||
const std::string nb::ImageError::type = "nb::ImageError";
|
|
||||||
const nb::ErrorCodeMap nb::ImageError::ErrorMessages = {
|
|
||||||
{ ImageErrorCodes::UNDEFINED, "Error" },
|
|
||||||
{ImageErrorCodes::OUT_OF_BOUNDS, "Out of bounds"}
|
|
||||||
};
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
#pragma clang diagnostic ignored "-Wint-to-pointer-cast"
|
|
||||||
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
|
|
||||||
|
|
||||||
#include <NBGraphics/Mesh.hpp>
|
|
||||||
|
|
||||||
namespace nb{
|
|
||||||
|
|
||||||
// class Mesh
|
|
||||||
Mesh::Mesh(
|
|
||||||
VertexDataPointerList vertexdata_,
|
|
||||||
unsigned int count_,
|
|
||||||
GLenum primitive_
|
|
||||||
) :
|
|
||||||
_primitive(primitive_),
|
|
||||||
_count(count_),
|
|
||||||
_vao(std::make_shared<VAO>(vertexdata_))
|
|
||||||
{}
|
|
||||||
|
|
||||||
Mesh::Mesh(
|
|
||||||
GLenum primitive_,
|
|
||||||
const std::shared_ptr<VAO>& vao_,
|
|
||||||
unsigned int count_
|
|
||||||
) :
|
|
||||||
_primitive(primitive_),
|
|
||||||
_count(count_),
|
|
||||||
_vao(vao_)
|
|
||||||
{}
|
|
||||||
|
|
||||||
Mesh::Mesh(
|
|
||||||
GLenum primitive_,
|
|
||||||
const VertexData& vertex_data_,
|
|
||||||
unsigned int count_
|
|
||||||
) : Mesh(primitive_, std::make_shared<VAO>(), count_) {
|
|
||||||
_vao->attributes({vertex_data_});
|
|
||||||
}
|
|
||||||
|
|
||||||
Mesh::Mesh(
|
|
||||||
GLenum primitive_,
|
|
||||||
const ByteVector& data_,
|
|
||||||
unsigned int count_,
|
|
||||||
const std::vector<VertexAttribute>& attributes_
|
|
||||||
) : Mesh(
|
|
||||||
primitive_,
|
|
||||||
VertexData(data_, attributes_),
|
|
||||||
count_
|
|
||||||
) {}
|
|
||||||
|
|
||||||
void Mesh::draw(unsigned int offset, unsigned int count) const {
|
|
||||||
_vao->bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glDrawArrays(_primitive, offset, count);
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// class InstancedMesh
|
|
||||||
|
|
||||||
void InstancedMesh::draw(unsigned int offset, unsigned instancecount) const {
|
|
||||||
_vao->bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glDrawArraysInstanced(_primitive, 0, _count, instancecount);
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// class IndexMeshes
|
|
||||||
|
|
||||||
void IndexedMesh::draw(unsigned int offset, unsigned numindices) const {
|
|
||||||
_vao->bind();
|
|
||||||
OPENGL_CALL(
|
|
||||||
glDrawElements(Mesh::_primitive, _count, _ebo->datatype(), (void*)offset)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
#include <NBGraphics/OGLObjects.hpp>
|
|
||||||
#include <NBGraphics/Window.hpp>
|
|
||||||
|
|
||||||
#ifndef GLENUMSTRPAIR
|
|
||||||
#define GLENUMSTRPAIR(x) {x, #x}
|
|
||||||
#endif // GLENUMSTRPAIR
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
const std::string OpenGLObjectError::type = "nb::OpenGLObjectError";
|
|
||||||
const ErrorCodeMap OpenGLObjectError::ErrorMessages = {
|
|
||||||
{ OpenGLObjectError::Codes::UNDEFINED, "Error" },
|
|
||||||
{OpenGLObjectError::Codes::HANGING_OBJECT, "Attempting to leave a hanging OpenGL object"},
|
|
||||||
{OpenGLObjectError::Codes::INVALID_OBJECT, "Attempting operation with invalid object"},
|
|
||||||
{OpenGLObjectError::Codes::INVALID_CONTEXT, "Object not valid with current OpengGL context"}
|
|
||||||
};
|
|
||||||
|
|
||||||
const std::string OpenGLError::type = "nb::OpenGLError";
|
|
||||||
const ErrorCodeMap OpenGLError::ErrorMessages = {
|
|
||||||
GLENUMSTRPAIR(GL_NO_ERROR),
|
|
||||||
GLENUMSTRPAIR(GL_INVALID_ENUM),
|
|
||||||
GLENUMSTRPAIR(GL_INVALID_ENUM),
|
|
||||||
GLENUMSTRPAIR(GL_INVALID_VALUE),
|
|
||||||
GLENUMSTRPAIR(GL_INVALID_OPERATION),
|
|
||||||
GLENUMSTRPAIR(GL_INVALID_FRAMEBUFFER_OPERATION),
|
|
||||||
GLENUMSTRPAIR(GL_OUT_OF_MEMORY),
|
|
||||||
GLENUMSTRPAIR(GL_STACK_UNDERFLOW),
|
|
||||||
GLENUMSTRPAIR(GL_STACK_OVERFLOW)
|
|
||||||
};
|
|
||||||
|
|
||||||
OpenGLError OpenGLError::status() {
|
|
||||||
return OpenGLError(glGetError());
|
|
||||||
}
|
|
||||||
|
|
||||||
OpenGLError OpenGLError::status(const std::string& note) {
|
|
||||||
return OpenGLError(glGetError(), note);
|
|
||||||
}
|
|
||||||
|
|
||||||
const ConstantMap<TypeCodes, int> TypeToGLSL = {
|
|
||||||
{TypeCodes::FLOAT16, GL_HALF_FLOAT},
|
|
||||||
{TypeCodes::FLOAT32, GL_FLOAT},
|
|
||||||
{TypeCodes::DOUBLE64, GL_DOUBLE},
|
|
||||||
{TypeCodes::INT8, GL_BYTE},
|
|
||||||
{TypeCodes::INT16, GL_SHORT},
|
|
||||||
{TypeCodes::INT32, GL_INT},
|
|
||||||
{TypeCodes::UINT8, GL_UNSIGNED_BYTE},
|
|
||||||
{TypeCodes::UINT16, GL_UNSIGNED_SHORT},
|
|
||||||
{TypeCodes::UINT32, GL_UNSIGNED_INT},
|
|
||||||
};
|
|
||||||
|
|
||||||
// class OpenGLObject
|
|
||||||
|
|
||||||
void OpenGLObject::checkObjectContextValidity() {
|
|
||||||
if (_arena != OGLWindow::GetCurrentObjectArena()) {
|
|
||||||
THROW(OpenGLObjectError(OpenGLObjectError::INVALID_CONTEXT));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
OpenGLObject::OpenGLObject(OpenGLObject&& rval) : _arena(rval._arena) {
|
|
||||||
checkObjectContextValidity();
|
|
||||||
*this = std::move(rval);
|
|
||||||
}
|
|
||||||
|
|
||||||
OpenGLObject::OpenGLObject() : _arena(OGLWindow::GetCurrentObjectArena()) {}
|
|
||||||
|
|
||||||
OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) {
|
|
||||||
rhs.checkObjectContextValidity();
|
|
||||||
if (_id) { THROW(OpenGLObjectError(Codes::HANGING_OBJECT)); }
|
|
||||||
_id = rhs._id;
|
|
||||||
rhs._id = 0;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
const GLEnumTableType GLenumTable = {
|
|
||||||
GLENUMSTRPAIR(GL_DRAW_FRAMEBUFFER),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_COMPLETE),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_UNDEFINED),
|
|
||||||
GLENUMSTRPAIR(GL_FRAMEBUFFER_UNSUPPORTED),
|
|
||||||
GLENUMSTRPAIR(GL_READ_FRAMEBUFFER),
|
|
||||||
GLENUMSTRPAIR(GL_RG),
|
|
||||||
GLENUMSTRPAIR(GL_RG32F),
|
|
||||||
GLENUMSTRPAIR(GL_RGB),
|
|
||||||
GLENUMSTRPAIR(GL_RGB8UI),
|
|
||||||
GLENUMSTRPAIR(GL_RGBA8UI),
|
|
||||||
GLENUMSTRPAIR(GL_RGBA),
|
|
||||||
GLENUMSTRPAIR(GL_ELEMENT_ARRAY_BUFFER),
|
|
||||||
GLENUMSTRPAIR(GL_UNSIGNED_INT),
|
|
||||||
GLENUMSTRPAIR(GL_UNSIGNED_SHORT),
|
|
||||||
GLENUMSTRPAIR(GL_UNSIGNED_BYTE),
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
#include <NBGraphics/ProgramPipeline.hpp>
|
|
||||||
|
|
||||||
namespace nb{
|
|
||||||
|
|
||||||
using ShaderErrCodes = ShaderError::Codes;
|
|
||||||
const std::string ShaderError::type = "nb::ShaderError";
|
|
||||||
const ErrorCodeMap ShaderError::ErrorMessages = {
|
|
||||||
{ShaderErrCodes::UNDEFINED, "Error"}
|
|
||||||
};
|
|
||||||
|
|
||||||
using ProgramErrCodes = ProgramError::Codes;
|
|
||||||
const std::string ProgramError::type = "nb::ProgramError";
|
|
||||||
const ErrorCodeMap ProgramError::ErrorMessages = {
|
|
||||||
{ProgramErrCodes::UNDEFINED, "Error"},
|
|
||||||
{ProgramErrCodes::LINKING_ERROR, "Linker error"}
|
|
||||||
};
|
|
||||||
|
|
||||||
// class Shader
|
|
||||||
|
|
||||||
Shader::Shader(GLenum target_, const std::string& source_)
|
|
||||||
: Shader(target_, std::vector<std::string>({source_})) {}
|
|
||||||
|
|
||||||
Shader::Shader(GLenum target_, const std::vector<std::string>& strings_)
|
|
||||||
: target(target_), _sources(strings_) {
|
|
||||||
declare();
|
|
||||||
compile();
|
|
||||||
}
|
|
||||||
|
|
||||||
Shader::Shader(Shader&& cpy)
|
|
||||||
: target(cpy.target), _success(cpy._success), _sources(cpy._sources) {
|
|
||||||
_id = cpy._id;
|
|
||||||
|
|
||||||
cpy._success = false;
|
|
||||||
cpy._sources = {};
|
|
||||||
cpy._id = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Shader::operator bool() { return success(); }
|
|
||||||
|
|
||||||
bool Shader::success() const {
|
|
||||||
return _success;
|
|
||||||
}
|
|
||||||
|
|
||||||
GLint Shader::status(GLenum parameter) const {
|
|
||||||
GLint param = 0;
|
|
||||||
OPENGL_CALL(glGetShaderiv(_id, parameter, ¶m));
|
|
||||||
return param;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Shader::log() const {
|
|
||||||
GLint logsize = status(GL_INFO_LOG_LENGTH);
|
|
||||||
char* log_ = new char[logsize];
|
|
||||||
OPENGL_CALL(glGetShaderInfoLog(_id, logsize, NULL, log_));
|
|
||||||
std::string ret(log_, logsize);
|
|
||||||
delete[] log_;
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
// class Program
|
|
||||||
|
|
||||||
Program::Program(SharedVector<Shader> shaders_) {
|
|
||||||
declare();
|
|
||||||
for (auto shad_ptr : shaders_) {
|
|
||||||
OPENGL_CALL(glAttachShader(_id, shad_ptr->id()));
|
|
||||||
}
|
|
||||||
OPENGL_CALL(glLinkProgram(_id));
|
|
||||||
_success = status(GL_LINK_STATUS);
|
|
||||||
if (!_success) {
|
|
||||||
WARN(log(), 0x0FE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Program::operator bool() { return _success; }
|
|
||||||
|
|
||||||
GLint Program::status(GLenum parameter) const {
|
|
||||||
GLint param = 0;
|
|
||||||
OPENGL_CALL(glGetProgramiv(_id, parameter, ¶m));
|
|
||||||
return param;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Program::log() const {
|
|
||||||
GLint logsize = status(GL_INFO_LOG_LENGTH);
|
|
||||||
char* log_ = new char[logsize];
|
|
||||||
OPENGL_CALL(glGetProgramInfoLog(_id, logsize, NULL, log_));
|
|
||||||
std::string ret(log_, logsize);
|
|
||||||
delete[] log_;
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Program::setUniform(const std::string& blockname, std::shared_ptr<UniformBuffer> buffer) {
|
|
||||||
declare();
|
|
||||||
auto idx = OPENGL_CALL(glGetUniformBlockIndex(id(), blockname.data()));
|
|
||||||
if (idx == GL_INVALID_INDEX) {
|
|
||||||
THROW("something");
|
|
||||||
}
|
|
||||||
this->setUniformBinding(blockname, buffer->bufferIndex());
|
|
||||||
OPENGL_CALL(glUniformBlockBinding(
|
|
||||||
id(),
|
|
||||||
idx,
|
|
||||||
_uniformBindings[blockname]
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
void Program::setUniformBinding(const std::string& blockname, GLuint index) {
|
|
||||||
_uniformBindings[blockname] = index;
|
|
||||||
}
|
|
||||||
|
|
||||||
GLuint Program::getUniformBinding(const std::string& blockname) const {
|
|
||||||
return _uniformBindings.at(blockname);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
#include <NBGraphics/Textures.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
// class RenderTarget
|
|
||||||
|
|
||||||
RenderTarget::RenderTarget(RenderTarget&& mv) : Target(mv.Target) {
|
|
||||||
*this = std::move(mv);
|
|
||||||
}
|
|
||||||
|
|
||||||
RenderTarget& RenderTarget::operator=(RenderTarget&& mv) {
|
|
||||||
if (mv.Target != Target) {
|
|
||||||
THROW(OpenGLObjectError(
|
|
||||||
OpenGLObjectError::INVALID_OBJECT,
|
|
||||||
"Cannot assign RenderTarget of different types."
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Base::operator=(std::move(mv));
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
// class Texture
|
|
||||||
Texture::Texture(GLenum target_) : Base(target_) {}
|
|
||||||
|
|
||||||
Texture::Texture(Texture&& mv) : Base(mv.Target) {
|
|
||||||
*this = std::move(mv);
|
|
||||||
}
|
|
||||||
|
|
||||||
Texture& Texture::operator=(Texture&& mv) {
|
|
||||||
Base::operator=(std::move(mv));
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
#include "VAOManager.hpp"
|
||||||
|
|
||||||
|
namespace NB {
|
||||||
|
|
||||||
|
using BufferManagerPointer = std::shared_ptr<Buffer>;
|
||||||
|
|
||||||
|
VAOManager::VAOManager() { glGenVertexArrays(1, &_id); }
|
||||||
|
|
||||||
|
VAOManager::VAOManager(
|
||||||
|
std::vector<BufferManagerPointer> vert_bufs,
|
||||||
|
BufferManagerPointer elmt_buf,
|
||||||
|
const VertexAttributeList& vert_attrs
|
||||||
|
) : VAOManager() {
|
||||||
|
_elmt_buffer = elmt_buf;
|
||||||
|
for (BufferManagerPointer vb : vert_bufs) {
|
||||||
|
_vert_buffers[vb->id()] = vb;
|
||||||
|
}
|
||||||
|
if (vert_attrs.size()!=0) {
|
||||||
|
generate(vert_attrs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
VAOManager::VAOManager(VAOManager&& rhs) { *this = std::move(rhs); }
|
||||||
|
|
||||||
|
VAOManager& VAOManager::operator=(VAOManager&& rhs) {
|
||||||
|
remove();
|
||||||
|
_vert_buffers = rhs._vert_buffers;
|
||||||
|
_elmt_buffer = rhs._elmt_buffer;
|
||||||
|
_vert_attrs = rhs._vert_attrs;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList VAOManager::getLayout() const { return _vert_attrs; }
|
||||||
|
|
||||||
|
GLuint VAOManager::id() const { return _id; }
|
||||||
|
|
||||||
|
bool VAOManager::isInitialized() const {
|
||||||
|
return _id && glIsVertexArray(_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
void VAOManager::remove() const {
|
||||||
|
bind();
|
||||||
|
for (int i{0}; i < _vert_attrs.size(); ++i) {
|
||||||
|
glDisableVertexAttribArray(i);
|
||||||
|
}
|
||||||
|
unbind();
|
||||||
|
glDisableVertexAttribArray(_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int VAOManager::vertSize(GLuint id) const {
|
||||||
|
unsigned int size = 0;
|
||||||
|
for (const VertexAttribute& va : _vert_attrs) {
|
||||||
|
if (va.ptr.buffer == id) {
|
||||||
|
size += va.GLSLSize * GLSLTypeSize(va.GLSLType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<BufferManagerPointer> VAOManager::getVertexBuffers() const {
|
||||||
|
std::vector<BufferManagerPointer> ret;
|
||||||
|
for (const auto& i : _vert_buffers) {
|
||||||
|
ret.emplace_back(i.second);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
RawVec VAOManager::attributeData(unsigned int i) {
|
||||||
|
if (i <= _vert_attrs.size()) {
|
||||||
|
throw std::out_of_range("No vertex attribute exists for specified index");
|
||||||
|
}
|
||||||
|
VertexAttribute attr = _vert_attrs[i];
|
||||||
|
BufferManagerPointer buffer = _vert_buffers[attr.ptr.buffer];
|
||||||
|
RawVec data = buffer->data();
|
||||||
|
unsigned int attr_size = attr.GLSLSize*GLSLTypeSize(attr.GLSLType);
|
||||||
|
RawVec ret((buffer->size()-attr.ptr.offset-attr_size)*attr_size/attr.ptr.stride);
|
||||||
|
int data_size = data.size();
|
||||||
|
for (int i{0}; i < data_size; ++i) {
|
||||||
|
if (isIndexInVertexAttribute(i, attr)) {
|
||||||
|
ret[i] = data[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
RawVec VAOManager::attributeData(unsigned int i, const RawVec& new_data) {
|
||||||
|
if (i >= _vert_attrs.size()) {
|
||||||
|
throw std::out_of_range("No vertex attribute exists for specified index.");
|
||||||
|
}
|
||||||
|
VertexAttribute attr = _vert_attrs[i];
|
||||||
|
BufferManagerPointer buffer = _vert_buffers[attr.ptr.buffer];
|
||||||
|
unsigned int attr_size = attr.GLSLSize*GLSLTypeSize(attr.GLSLType);
|
||||||
|
unsigned int offset = attr.ptr.offset;
|
||||||
|
unsigned int num_verts = buffer->size() / vertSize(buffer->id());
|
||||||
|
if (num_verts*attr_size != new_data.size()) {
|
||||||
|
// WHY HERE????
|
||||||
|
THROW_VAO_ERROR(
|
||||||
|
"Input data size of " + std::to_string(new_data.size())
|
||||||
|
+ " does not match data size for requested vertex attribute of total size " + std::to_string(num_verts*attr_size)
|
||||||
|
+ "."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
uint64_t pos = uint64_t(new_data.data());
|
||||||
|
for (int i{0}; i<num_verts; i++) {
|
||||||
|
buffer->data((void*)(pos+i*attr_size), offset+i*attr.ptr.stride, attr_size);
|
||||||
|
}
|
||||||
|
return RawVec(new_data);
|
||||||
|
}
|
||||||
|
|
||||||
|
void VAOManager::bind() const {
|
||||||
|
glBindVertexArray(_id);
|
||||||
|
if (_elmt_buffer) { _elmt_buffer->bind(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
void VAOManager::unbind() const {
|
||||||
|
glBindVertexArray(0);
|
||||||
|
if (_elmt_buffer) { _elmt_buffer->unbind(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
void VAOManager::addVBO(BufferManagerPointer vert_buf) {
|
||||||
|
GLuint vert_id = vert_buf->id();
|
||||||
|
if (_vert_buffers.find(vert_id) == _vert_buffers.end()) {
|
||||||
|
_vert_buffers[vert_buf->id()] = vert_buf;
|
||||||
|
} else {
|
||||||
|
THROW_VAO_ERROR("Attempting to add identical VBO id of " + std::to_string(vert_id) + ".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void VAOManager::changeEBO(BufferManagerPointer ebo) {
|
||||||
|
_elmt_buffer = ebo;
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList VAOManager::addVertexAttributes(const VertexAttributeList& vert_attrs) {
|
||||||
|
VertexAttributeList curr_vas = _vert_attrs;
|
||||||
|
curr_vas.insert(curr_vas.end(), vert_attrs.begin(), vert_attrs.end());
|
||||||
|
try {
|
||||||
|
throw checkValid(curr_vas);
|
||||||
|
} catch (VAOError vaoe) {
|
||||||
|
if (vaoe.error) {
|
||||||
|
THROW_VAO_ERROR(vaoe.what());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_vert_attrs = curr_vas;
|
||||||
|
generate();
|
||||||
|
return _vert_attrs;
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList VAOManager::addVertexAttributes(VertexAttribute vert_attr) {
|
||||||
|
return addVertexAttributes({vert_attr});
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList VAOManager::generate() {
|
||||||
|
bind();
|
||||||
|
unsigned int num_attrs = _vert_attrs.size();
|
||||||
|
VertexAttribute* va;
|
||||||
|
for (int i = 0; i < num_attrs; ++i) {
|
||||||
|
va = &(_vert_attrs[i]);
|
||||||
|
_vert_buffers[va->ptr.buffer]->bind();
|
||||||
|
glVertexAttribPointer(
|
||||||
|
i,
|
||||||
|
va->GLSLSize,
|
||||||
|
va->GLSLType,
|
||||||
|
va->GLSLNormalization,
|
||||||
|
va->ptr.stride,
|
||||||
|
(void*)va->ptr.offset
|
||||||
|
);
|
||||||
|
glVertexAttribDivisor(i, va->ptr.divisor);
|
||||||
|
glEnableVertexAttribArray(i);
|
||||||
|
}
|
||||||
|
if (_elmt_buffer != nullptr) {
|
||||||
|
_elmt_buffer->bind();
|
||||||
|
}
|
||||||
|
unbind();
|
||||||
|
return _vert_attrs;
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList VAOManager::generate(VertexAttributeList vert_attrs) {
|
||||||
|
try {
|
||||||
|
throw checkValid(vert_attrs);
|
||||||
|
} catch (VAOError vaoe) {
|
||||||
|
if (vaoe.error) {
|
||||||
|
THROW_VAO_ERROR(vaoe.what());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_vert_attrs.swap(vert_attrs);
|
||||||
|
return generate();
|
||||||
|
}
|
||||||
|
|
||||||
|
VertexAttributeList VAOManager::changeLayout(unsigned int i, VertexAttributePointer vap) {
|
||||||
|
_vert_attrs[i].ptr = vap;
|
||||||
|
bind();
|
||||||
|
const VertexAttribute* va = &(_vert_attrs[i]);
|
||||||
|
glDisableVertexAttribArray(i);
|
||||||
|
_vert_buffers[va->ptr.buffer]->bind();
|
||||||
|
glVertexAttribPointer(
|
||||||
|
_id,
|
||||||
|
va->GLSLSize,
|
||||||
|
va->GLSLType,
|
||||||
|
va->GLSLNormalization,
|
||||||
|
va->ptr.stride,
|
||||||
|
(void*)va->ptr.offset
|
||||||
|
);
|
||||||
|
glVertexAttribDivisor(i, va->ptr.divisor);
|
||||||
|
glEnableVertexAttribArray(i);
|
||||||
|
unbind();
|
||||||
|
return _vert_attrs;
|
||||||
|
}
|
||||||
|
|
||||||
|
VAOError VAOManager::checkValid(const VertexAttributeList& vert_attrs) {
|
||||||
|
GLuint va_id;
|
||||||
|
unsigned int num_attrs = vert_attrs.size();
|
||||||
|
for (int i = 0; i < num_attrs; ++i) {
|
||||||
|
va_id = vert_attrs[i].ptr.buffer;
|
||||||
|
if (_vert_buffers.find(va_id) == _vert_buffers.cend()) {
|
||||||
|
return VAOError("Attempting to point to unknown VBO of id " + std::to_string(va_id) +
|
||||||
|
" at Vertex Attribute " + std::to_string(i) + ".");
|
||||||
|
}
|
||||||
|
if (vert_attrs[i].ptr.stride<0) {
|
||||||
|
return VAOError("Invalid stride value at Vertex Attribute " + std::to_string(i) + ".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return VAOError(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace NB
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
#pragma clang diagnostic ignored "-Wint-to-pointer-cast"
|
|
||||||
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
|
|
||||||
|
|
||||||
#include <NBGraphics/VertexArray.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
using VAOErrorCodes = VAOError::Codes;
|
|
||||||
const std::string VAOError::type = "nb::VAOError";
|
|
||||||
const ErrorCodeMap VAOError::ErrorMessages = {
|
|
||||||
{ VAOErrorCodes::UNDEFINED, "Error" },
|
|
||||||
{ VAOErrorCodes::INVALID_ATTRIBUTE, "Targeting invalid attribute"}
|
|
||||||
};
|
|
||||||
|
|
||||||
using VertexCodes = VertexError::Codes;
|
|
||||||
const std::string VertexError::type = "nb::VertexError";
|
|
||||||
const ErrorCodeMap VertexError::ErrorMessages = {
|
|
||||||
{ VertexError::UNDEFINED, "Error" },
|
|
||||||
{ VertexError::MISALIGNED_DATA, "Data does not match vertex layout"}
|
|
||||||
};
|
|
||||||
|
|
||||||
VAO::VAO(const VertexDataPointerList& attr_ptrs) {
|
|
||||||
attributes(attr_ptrs);
|
|
||||||
}
|
|
||||||
|
|
||||||
VAO::VAO(VAO&& other) {
|
|
||||||
*this = std::move(other);
|
|
||||||
}
|
|
||||||
|
|
||||||
VAO& VAO::operator=(VAO&& rhs) {
|
|
||||||
OpenGLObject::operator=(std::move(rhs));
|
|
||||||
_vertexdata = rhs._vertexdata;
|
|
||||||
rhs._vertexdata = {};
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
VertexDataPointerList VAO::attributes() const {
|
|
||||||
return _vertexdata;
|
|
||||||
}
|
|
||||||
|
|
||||||
VertexDataPointerList VAO::attributes(const VertexDataPointerList& vertdatalist) {
|
|
||||||
declare();
|
|
||||||
disable();
|
|
||||||
_vertexdata = vertdatalist;
|
|
||||||
bind();
|
|
||||||
for (const auto vdata : _vertexdata) {
|
|
||||||
OPENGL_CALL(glBindBuffer(GL_ARRAY_BUFFER, vdata.vertexdata->data->id()));
|
|
||||||
for (const auto attr : vdata.vertexdata->attributes) {
|
|
||||||
GLuint idx = vdata.index;
|
|
||||||
OPENGL_CALL(glVertexAttribPointer(
|
|
||||||
idx,
|
|
||||||
attr.size,
|
|
||||||
TypeToGLSL[attr.type],
|
|
||||||
attr.normalized,
|
|
||||||
attr.layout.stride,
|
|
||||||
(const void*) attr.layout.offset
|
|
||||||
));
|
|
||||||
OPENGL_CALL(glEnableVertexAttribArray(idx));
|
|
||||||
if (attr.layout.divisor) {
|
|
||||||
OPENGL_CALL(glVertexAttribDivisor(idx, attr.layout.divisor));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
unbind();
|
|
||||||
enable();
|
|
||||||
return _vertexdata;
|
|
||||||
}
|
|
||||||
|
|
||||||
VertexDataPointerList VAO::attributes(const VertexDataList& vertdatalist) {
|
|
||||||
VertexDataPointerList vdatas;
|
|
||||||
for (unsigned int i = 0; i < vertdatalist.size(); ++i) {
|
|
||||||
vdatas.emplace_back(VertexDataPointer{
|
|
||||||
std::make_shared<VertexData>(vertdatalist[i]),
|
|
||||||
i
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return attributes(vdatas);
|
|
||||||
}
|
|
||||||
|
|
||||||
VertexDataPointer VAO::attribute(GLuint idx) const {
|
|
||||||
for (auto vdata : _vertexdata) {
|
|
||||||
if (idx == vdata.index) {
|
|
||||||
return vdata;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
THROW(VAOError(Codes::INVALID_ATTRIBUTE));
|
|
||||||
}
|
|
||||||
|
|
||||||
void VAO::enable() const {
|
|
||||||
if (_id) {
|
|
||||||
bind();
|
|
||||||
for(auto vdata : _vertexdata) {
|
|
||||||
OPENGL_CALL(glEnableVertexAttribArray(vdata.index));
|
|
||||||
}
|
|
||||||
unbind();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void VAO::enable(GLuint idx) const {
|
|
||||||
if(_id) {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(glEnableVertexAttribArray(attribute(idx).index));
|
|
||||||
unbind();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void VAO::disable() const {
|
|
||||||
if(_id) {
|
|
||||||
bind();
|
|
||||||
for(auto vdata : _vertexdata) {
|
|
||||||
OPENGL_CALL(glDisableVertexAttribArray(vdata.index));
|
|
||||||
}
|
|
||||||
unbind();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void VAO::disable(GLuint idx) const {
|
|
||||||
if(_id) {
|
|
||||||
bind();
|
|
||||||
OPENGL_CALL(glDisableVertexAttribArray(attribute(idx).index));
|
|
||||||
unbind();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
#include <NBGraphics/VertexData.hpp>
|
|
||||||
|
|
||||||
namespace nb {
|
|
||||||
|
|
||||||
VertexData::VertexData(
|
|
||||||
std::shared_ptr<Buffer> data_,
|
|
||||||
const std::vector<VertexAttribute>& attrs_
|
|
||||||
) : data(data_), attributes(attrs_) {}
|
|
||||||
|
|
||||||
VertexData::VertexData(
|
|
||||||
const ByteVector& data_,
|
|
||||||
const std::vector<VertexAttribute>& attrs_
|
|
||||||
) : data(std::make_shared<Buffer>(GL_ARRAY_BUFFER, data_)),
|
|
||||||
attributes(attrs_) {}
|
|
||||||
|
|
||||||
} // namespace nb
|
|
||||||
+130
-162
@@ -1,203 +1,171 @@
|
|||||||
#include <NBGraphics/Window.hpp>
|
#include "Window.hpp"
|
||||||
|
|
||||||
namespace nb {
|
namespace nb {
|
||||||
|
|
||||||
using GLFWCodes = GLFWError::Codes;
|
std::map<GLFWwindow*, Window*> Window::WindowContexts = {};
|
||||||
const std::string GLFWError::type = "nb::GLFWError";
|
std::map<int, int> Window::GLFWHints = {};
|
||||||
const ErrorCodeMap GLFWError::ErrorMessages = {
|
bool Window::StrictInitialization = true;
|
||||||
{GLFWCodes::UNDEFINED, "Error"},
|
bool Window::_glfw_init = false;
|
||||||
{GLFWCodes::INIT_FAILED, "GLFW initialization failed"},
|
Window* Window::_current = nullptr;
|
||||||
{GLFWCodes::GLFW_INTIALIZED, "GLFW has already been initialized"},
|
static std::map<int, int> defailt_window_hints = {
|
||||||
{GLFWCodes::GLAD_FAILED, "GLAD initialization failed"},
|
{GLFW_CONTEXT_VERSION_MAJOR, 3},
|
||||||
{GLFWCodes::NOT_MAIN, "Action can only be done on main thread"},
|
{GLFW_CONTEXT_VERSION_MINOR, 1},
|
||||||
{GLFWCodes::WINDOW_FAILED, "Failed to initialize window"}
|
{GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE}
|
||||||
|
#ifdef _NB_GL_DEBUG_ON
|
||||||
|
, {GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE}
|
||||||
|
#endif
|
||||||
};
|
};
|
||||||
|
|
||||||
// class OGLWindow
|
GLError::GLError(const std::string& msg) : std::runtime_error(msg) {}
|
||||||
|
|
||||||
std::atomic<bool> OGLWindow::_glfwInitialized = false;
|
WindowError::WindowError(const std::string &msg) : std::runtime_error(msg) {}
|
||||||
thread_local GLFWwindow* OGLWindow::_currWindow = nullptr;
|
|
||||||
thread_local const GLFWwindow* OGLWindow::_currArena = nullptr;
|
|
||||||
std::atomic<unsigned int> OGLWindow::_count = 0;
|
|
||||||
|
|
||||||
bool OGLWindow::InitGLFW(const std::vector<GLFWHint>& hints) {
|
int Window::getGLFWHint(int hint_key) {
|
||||||
if (nb::MainTID != GetTID()) {
|
if (GLFWHints.find(hint_key) == GLFWHints.end()) {
|
||||||
THROW(GLFWError(GLFWError::NOT_MAIN));
|
return 0;
|
||||||
}
|
|
||||||
if (!IsGLFWInitialized()) {
|
|
||||||
for (const auto& hint : hints) {
|
|
||||||
glfwInitHint(hint[0], hint[1]);
|
|
||||||
}
|
|
||||||
if (glfwInit()) {
|
|
||||||
OGLWindow::_glfwInitialized.store(true, std::memory_order_release);
|
|
||||||
} else {
|
} else {
|
||||||
THROW(GLFWError(GLFWError::INIT_FAILED));
|
return GLFWHints.at(hint_key);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return IsGLFWInitialized();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool OGLWindow::TerminateGLFW() {
|
int Window::setGLFWHint(int hint_key, int hint_val) {
|
||||||
if (nb::MainTID != GetTID()) {
|
if (Window::_glfw_init) {
|
||||||
THROW(GLFWError(GLFWError::NOT_MAIN));
|
throw GLError("Cannot set GLFW hint after window is initialized.");
|
||||||
|
} else {
|
||||||
|
GLFWHints[hint_key] = hint_val;
|
||||||
}
|
}
|
||||||
if (IsGLFWInitialized()) {
|
return GLFWHints[hint_key];
|
||||||
|
}
|
||||||
|
|
||||||
|
Window* Window::getCurrent() {
|
||||||
|
return _current;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Window::checkKillGLFW() {
|
||||||
|
if(Window::WindowContexts.size() == 0 && _glfw_init) {
|
||||||
glfwTerminate();
|
glfwTerminate();
|
||||||
OGLWindow::_glfwInitialized.store(false, std::memory_order_release);
|
Window::_glfw_init = false;
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
return !IsGLFWInitialized();
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void OGLWindow::SetHintInteger(const std::array<int, 2>& hint) {
|
Window::Window(const uint16_t x, const uint16_t y, const char* initName, GLFWmonitor* initMonitor, GLFWwindow* initWindow) {
|
||||||
CheckForMainThread();
|
if (!Window::_glfw_init) {
|
||||||
glfwWindowHint(hint[0], hint[1]);
|
for (const auto& hint : Window::GLFWHints) {
|
||||||
}
|
glfwInitHint(hint.first, hint.second);
|
||||||
|
}
|
||||||
void OGLWindow::SetHintString(const std::tuple<int, std::string>& hint) {
|
int glfwResponse = glfwInit();
|
||||||
CheckForMainThread();
|
if (glfwResponse) {
|
||||||
glfwWindowHintString(std::get<0>(hint), std::get<1>(hint).c_str());
|
Window::_glfw_init = true;
|
||||||
}
|
|
||||||
|
|
||||||
GLFWwindow* OGLWindow::MakeCurrent(const std::shared_ptr<OGLWindow>& window) {
|
|
||||||
auto tmp = _currWindow;
|
|
||||||
if (window) {
|
|
||||||
_currWindow = window->getWindowPtr();
|
|
||||||
_currArena = window->_arena;
|
|
||||||
} else {
|
} else {
|
||||||
_currWindow = nullptr;
|
if (Window::StrictInitialization) {
|
||||||
_currArena = nullptr;
|
throw GLError("Failed to load GLFW with glfwInit()="+std::to_string(glfwResponse)+".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
windowSize = {x, y};
|
||||||
|
_aspect_ratio = float(x)/float(y);
|
||||||
|
windowName = std::string(initName);
|
||||||
|
monitor = initMonitor;
|
||||||
|
shareWindow = initWindow;
|
||||||
|
|
||||||
|
for (const auto& hint: defailt_window_hints) {
|
||||||
|
windowHints[hint.first] = hint.second;
|
||||||
}
|
}
|
||||||
glfwMakeContextCurrent(_currWindow);
|
|
||||||
return tmp;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<OGLWindow> OGLWindow::CreateWindow(
|
Window::Window(const std::array<uint16_t, 2> initSize, const char* initName, GLFWmonitor* initMonitor, GLFWwindow* initWindow) :
|
||||||
unsigned int x,
|
Window(initSize[0], initSize[1], initName, initMonitor, initWindow){}
|
||||||
unsigned int y,
|
|
||||||
const std::string& title,
|
Window::~Window() {
|
||||||
const std::vector<std::array<int, 2>>& integerHints,
|
glfwSetWindowShouldClose(window, true);
|
||||||
const std::vector<std::tuple<int, std::string>>& stringHints
|
glfwDestroyWindow(window);
|
||||||
) {
|
Window::WindowContexts.erase(window);
|
||||||
return std::shared_ptr<OGLWindow>( new OGLWindow(
|
if (Window::WindowContexts.size()==0) {
|
||||||
x,
|
glfwTerminate();
|
||||||
y,
|
}
|
||||||
title,
|
|
||||||
integerHints,
|
|
||||||
stringHints
|
|
||||||
) );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<OGLWindow> OGLWindow::CreateSharedWindow(
|
void Window::setCurrent() {
|
||||||
unsigned int x,
|
_current = this;
|
||||||
unsigned int y,
|
glfwMakeContextCurrent(window);
|
||||||
const std::string& title,
|
|
||||||
std::shared_ptr<OGLWindow> sharingWindow,
|
|
||||||
const std::vector<std::array<int, 2>>& integerHints,
|
|
||||||
const std::vector<std::tuple<int, std::string>>& stringHints
|
|
||||||
) {
|
|
||||||
return std::shared_ptr<OGLWindow>( new OGLWindow(
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
title,
|
|
||||||
integerHints,
|
|
||||||
stringHints,
|
|
||||||
sharingWindow->getWindowPtr()
|
|
||||||
) );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
OGLWindow::OGLWindow(
|
int Window::getWindowHint(int hint_key) const {
|
||||||
unsigned int x,
|
if (windowHints.find(hint_key) == windowHints.end()) {
|
||||||
unsigned int y,
|
return 0;
|
||||||
const std::string& title,
|
} else {
|
||||||
const std::vector<std::array<int, 2>>& integerHints,
|
return windowHints.at(hint_key);
|
||||||
const std::vector<std::tuple<int, std::string>>& stringHints,
|
|
||||||
GLFWwindow* sharingContext
|
|
||||||
) : _title(title) {
|
|
||||||
CheckForMainThread();
|
|
||||||
InitGLFW();
|
|
||||||
for (const auto& hint : integerHints) {
|
|
||||||
SetHintInteger(hint);
|
|
||||||
}
|
}
|
||||||
for (const auto& hint : stringHints) {
|
}
|
||||||
SetHintString(hint);
|
|
||||||
|
int Window::setWindowHint(int hint_key, int hint_val) {
|
||||||
|
if (_init) {
|
||||||
|
throw WindowError("Cannot set window hint after window is initialized.");
|
||||||
|
} else {
|
||||||
|
windowHints[hint_key] = hint_val;
|
||||||
}
|
}
|
||||||
_window_ptr = glfwCreateWindow(
|
return windowHints[hint_key];
|
||||||
x,
|
}
|
||||||
y,
|
|
||||||
_title.c_str(),
|
int Window::init() {
|
||||||
NULL,
|
if (!_glfw_init) {
|
||||||
sharingContext
|
throw GLError("GLFW has not been initialized.");
|
||||||
|
}
|
||||||
|
for (const auto& hint : windowHints) {
|
||||||
|
glfwWindowHint(hint.first, hint.second);
|
||||||
|
}
|
||||||
|
|
||||||
|
window = glfwCreateWindow(windowSize[0], windowSize[1], windowName.c_str(), monitor, shareWindow);
|
||||||
|
if (window == NULL) {
|
||||||
|
Window::WindowContexts.erase(window);
|
||||||
|
if (Window::WindowContexts.size()==0 && Window::_glfw_init) { glfwTerminate(); }
|
||||||
|
if (Window::StrictInitialization) {
|
||||||
|
throw WindowError("Could not create window in glfwCreateWindow().");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
glfwMakeContextCurrent(window);
|
||||||
|
Window::WindowContexts[window] = this;
|
||||||
|
|
||||||
|
gladResponse = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
|
||||||
|
if (!gladResponse) {
|
||||||
|
Window::checkKillGLFW();
|
||||||
|
if (Window::StrictInitialization) {
|
||||||
|
throw GLError("Failed to load GLAD with \
|
||||||
|
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)="+\
|
||||||
|
std::to_string(gladResponse)+"."
|
||||||
);
|
);
|
||||||
if (_window_ptr == NULL) {
|
|
||||||
THROW(GLFWError(GLFWError::Codes::WINDOW_FAILED));
|
|
||||||
}
|
|
||||||
_arena = _window_ptr;
|
|
||||||
auto tmp = makeCurrent();
|
|
||||||
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
|
|
||||||
THROW(GLFWError(GLFWError::Codes::GLAD_FAILED));
|
|
||||||
}
|
|
||||||
glfwMakeContextCurrent(tmp);
|
|
||||||
OGLWindow::_count.fetch_add(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
OGLWindow::~OGLWindow() {
|
|
||||||
CheckForMainThread();
|
|
||||||
if (_window_ptr) {
|
|
||||||
if (_window_ptr == _currWindow) {
|
|
||||||
_currWindow = nullptr;
|
|
||||||
_currArena = nullptr;
|
|
||||||
}
|
|
||||||
glfwDestroyWindow(_window_ptr);
|
|
||||||
_count.fetch_add(-1);
|
|
||||||
if (!_count.load()) {
|
|
||||||
TerminateGLFW();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_init = true;
|
||||||
|
glViewport(0, 0, windowSize[0], windowSize[1]);
|
||||||
|
return gladResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
void OGLWindow::detachWindow() {
|
GLFWwindow* Window::getWindow() const {
|
||||||
_title = "";
|
return window;
|
||||||
_window_ptr = nullptr;
|
|
||||||
_arena = nullptr;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int OGLWindow::getWindowAttribute(int attr) const {
|
float Window::getAspectRatio() const { return _aspect_ratio; }
|
||||||
CheckForMainThread();
|
|
||||||
return glfwGetWindowAttrib(_window_ptr, attr);
|
std::array<uint16_t, 2> Window::getSize() const {
|
||||||
|
return windowSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::array<int, 2> OGLWindow::getSize() const {
|
std::string Window::getName() const {
|
||||||
CheckForMainThread();
|
return windowName;
|
||||||
int x, y;
|
|
||||||
glfwGetWindowSize(_window_ptr, &x, &y);
|
|
||||||
return {x, y};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool OGLWindow::shouldClose() const {
|
void Window::resize(const std::array<uint16_t, 2> newSize) {
|
||||||
CheckForMainThread();
|
windowSize = newSize;
|
||||||
return glfwWindowShouldClose(_window_ptr);
|
_aspect_ratio = float(newSize[0]) / float(newSize[1]);
|
||||||
|
glViewport(0, 0, windowSize[0], windowSize[1]);
|
||||||
|
glfwSetWindowSize(window, windowSize[0], windowSize[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
void OGLWindow::shouldClose(bool val) {
|
void Window::resize(const uint16_t x, const uint16_t y) { resize({x, y}); }
|
||||||
CheckForMainThread();
|
|
||||||
glfwSetWindowShouldClose(_window_ptr, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
GLFWwindow* OGLWindow::makeCurrent() const {
|
|
||||||
auto tmp = glfwGetCurrentContext();
|
|
||||||
glfwMakeContextCurrent(_window_ptr);
|
|
||||||
return tmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
void OGLWindow::setSize(unsigned int x, unsigned int y) {
|
|
||||||
CheckForMainThread();
|
|
||||||
glfwSetWindowSize(_window_ptr, x, y);
|
|
||||||
}
|
|
||||||
|
|
||||||
void OGLWindow::setTitle(const std::string& name) {
|
|
||||||
CheckForMainThread();
|
|
||||||
_title = name;
|
|
||||||
glfwSetWindowTitle(_window_ptr, _title.c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,742 @@
|
|||||||
|
#include "Shader.h"
|
||||||
|
|
||||||
|
// #define _PREPROC_FUNC_PARAM_NAMES_ (const ShaderPreprocessor& proc, ShaderUnit& shad, unsigned int linenum, const std::string& line, std::vector<uint8_t>& params)
|
||||||
|
|
||||||
|
namespace NB{
|
||||||
|
|
||||||
|
File::FilePath get_file_path(std::string name) {
|
||||||
|
const std::vector<char> allowed_special_chars = {
|
||||||
|
'.', '!', '#', '$', '%', '&', '\'', '(', ')', '+', ',', '-', ';', '=', '@', '[', ']', '^', '_', '`', '~'
|
||||||
|
};
|
||||||
|
std::vector<std::string> path = {""};
|
||||||
|
for (const char c : name) {
|
||||||
|
if (c == '/' || c == '\\') {
|
||||||
|
path.push_back("");
|
||||||
|
} else if (std::isalnum(c)) {
|
||||||
|
path.back() += c;
|
||||||
|
} else {
|
||||||
|
bool spec_char_found = false;
|
||||||
|
for (const char sc : allowed_special_chars) {
|
||||||
|
if (c == sc) {
|
||||||
|
path.back() += c;
|
||||||
|
spec_char_found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!spec_char_found) {
|
||||||
|
throw std::runtime_error("'" + name + "' is not valid filepath.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
File::FilePath ret;
|
||||||
|
for (const auto& tk : path) {
|
||||||
|
if (tk == path.back()) {
|
||||||
|
size_t period = tk.find(".");
|
||||||
|
if (period == std::string::npos) {
|
||||||
|
ret.basename = tk;
|
||||||
|
ret.ext = "";
|
||||||
|
} else {
|
||||||
|
ret.basename = tk.substr(0, period);
|
||||||
|
ret.ext = tk.substr(period);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ret.dir += tk + "/";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShaderPreprocessorError class
|
||||||
|
ShaderPreprocessorError::ShaderPreprocessorError(
|
||||||
|
const std::string& msg,
|
||||||
|
const std::string& file,
|
||||||
|
int line
|
||||||
|
) : code(Codes::UNDEFINED), std::runtime_error(formatDebugString(msg, file, line)) {}
|
||||||
|
|
||||||
|
ShaderPreprocessorError::ShaderPreprocessorError(
|
||||||
|
Codes err_code,
|
||||||
|
const std::string& arg,
|
||||||
|
const std::string& file,
|
||||||
|
int line
|
||||||
|
) : code(err_code), std::runtime_error(formatDebugString(errorCodeParser(err_code, arg), file, line)) {}
|
||||||
|
|
||||||
|
std::string ShaderPreprocessorError::errorCodeParser(Codes err_code, const std::string& arg) {
|
||||||
|
switch(err_code) {
|
||||||
|
case Codes::FILE_NOT_FOUND:
|
||||||
|
return "File '" + arg + "' not found.";
|
||||||
|
case Codes::BUILTIN_NOT_FOUND:
|
||||||
|
return "Built-in '" + arg + "' not found.";
|
||||||
|
case Codes::CUSTOM:
|
||||||
|
case Codes::UNDEFINED:
|
||||||
|
return arg;
|
||||||
|
case Codes::NONE:
|
||||||
|
default:
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShaderError class
|
||||||
|
ShaderError::ShaderError(
|
||||||
|
const std::string& msg,
|
||||||
|
const char* shad,
|
||||||
|
const std::string& file,
|
||||||
|
int line
|
||||||
|
) : std::runtime_error(formatString(msg, shad, file, line)) {}
|
||||||
|
|
||||||
|
std::string ShaderError::formatString(
|
||||||
|
const std::string& msg,
|
||||||
|
const char* shad,
|
||||||
|
const std::string& file,
|
||||||
|
int line
|
||||||
|
) {
|
||||||
|
std::stringstream ret;
|
||||||
|
if (file != "") {
|
||||||
|
ret << "In file " << file;
|
||||||
|
if (line >= 0) {
|
||||||
|
ret << " at line " << line;
|
||||||
|
}
|
||||||
|
ret << ":\n\t";
|
||||||
|
}
|
||||||
|
ret << msg;
|
||||||
|
if (shad != nullptr) {
|
||||||
|
ret << " with shader error: " << shad;
|
||||||
|
}
|
||||||
|
return ret.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShaderPreprocessor class
|
||||||
|
std::string ShaderPreprocessor::TokenName(const ShaderPreprocessor::TokenType& x) {
|
||||||
|
switch(x) {
|
||||||
|
case TK:
|
||||||
|
return "Token";
|
||||||
|
break;
|
||||||
|
case DR:
|
||||||
|
return "Directive";
|
||||||
|
break;
|
||||||
|
case WS:
|
||||||
|
return "Whitespace";
|
||||||
|
break;
|
||||||
|
case NL:
|
||||||
|
return "NewLine";
|
||||||
|
break;
|
||||||
|
case LC:
|
||||||
|
return "LineComment";
|
||||||
|
break;
|
||||||
|
case BC:
|
||||||
|
return "BlockComment";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return "Unrecognized";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderPreprocessor::ShaderPreprocessor() {}
|
||||||
|
|
||||||
|
File ShaderPreprocessor::loadFromBase(const std::string path, const std::string base) const {
|
||||||
|
File ret;
|
||||||
|
std::ifstream filestream;
|
||||||
|
filestream.open(base + path);
|
||||||
|
if (filestream.is_open()) {
|
||||||
|
ret.path = get_file_path(base + path);
|
||||||
|
ret.src << filestream.rdbuf();
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
filestream.close();
|
||||||
|
std::string ext;
|
||||||
|
for (const auto& kv : AcceptedExtensions) {
|
||||||
|
ext = kv.first;
|
||||||
|
filestream.open(base + path + ext);
|
||||||
|
if (filestream.is_open()) {
|
||||||
|
ret.path = get_file_path(base + path + ext);
|
||||||
|
ret.src << filestream.rdbuf();
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
filestream.close();
|
||||||
|
}
|
||||||
|
throw ShaderPreprocessorError(Codes::FILE_NOT_FOUND, base + path);
|
||||||
|
}
|
||||||
|
|
||||||
|
File ShaderPreprocessor::loadFromDirectories(const std::string name) const {
|
||||||
|
File ret;
|
||||||
|
std::ifstream fstream;
|
||||||
|
for (const std::string& path : Directories) {
|
||||||
|
fstream.open(path + name);
|
||||||
|
if (fstream.is_open()) {
|
||||||
|
ret.path = get_file_path(path + name);
|
||||||
|
ret.src << fstream.rdbuf();
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
fstream.close();
|
||||||
|
}
|
||||||
|
throw ShaderPreprocessorError(Codes::FILE_NOT_FOUND, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
File ShaderPreprocessor::load(const std::string path, bool builtin_first) const {
|
||||||
|
if(builtin_first) {
|
||||||
|
return load_BuiltInFirst(path);
|
||||||
|
}
|
||||||
|
return load_FilesFirst(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
File ShaderPreprocessor::loadFromBuiltIn(const std::string name) const {
|
||||||
|
File ret;
|
||||||
|
//std::stringstream ret;
|
||||||
|
decltype(BuiltIns)::const_iterator builtin_it = BuiltIns.find(name);
|
||||||
|
if (builtin_it != BuiltIns.end()) {
|
||||||
|
ret.path = File::FilePath{"builtin:", name, ""};
|
||||||
|
ret.src << builtin_it->second;
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
throw ShaderPreprocessorError(Codes::BUILTIN_NOT_FOUND, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
File ShaderPreprocessor::load_FilesFirst(const std::string path) const {
|
||||||
|
try {
|
||||||
|
return loadFromBase(path);
|
||||||
|
} catch (ShaderPreprocessorError e) {
|
||||||
|
if (e.code == Codes::FILE_NOT_FOUND) {
|
||||||
|
try {
|
||||||
|
return loadFromDirectories(path);
|
||||||
|
} catch (ShaderPreprocessorError f) {
|
||||||
|
if (f.code == Codes::FILE_NOT_FOUND) {
|
||||||
|
try {
|
||||||
|
return loadFromBuiltIn(path);
|
||||||
|
} catch(ShaderPreprocessorError g) {
|
||||||
|
if (g.code == Codes::BUILTIN_NOT_FOUND) {
|
||||||
|
throw ShaderPreprocessorError(Codes::FILE_NOT_FOUND, path);
|
||||||
|
} else { throw g; }
|
||||||
|
}
|
||||||
|
} else { throw f; }
|
||||||
|
}
|
||||||
|
} else { throw e; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
File ShaderPreprocessor::load_BuiltInFirst(const std::string path) const {
|
||||||
|
try {
|
||||||
|
return loadFromBuiltIn(path);
|
||||||
|
} catch (ShaderPreprocessorError f) {
|
||||||
|
if (f.code == Codes::BUILTIN_NOT_FOUND) {
|
||||||
|
try {
|
||||||
|
return loadFromDirectories(path);
|
||||||
|
} catch (ShaderPreprocessorError e) {
|
||||||
|
if (e.code == Codes::FILE_NOT_FOUND) {
|
||||||
|
return loadFromBase(path);
|
||||||
|
} else {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<ShaderPreprocessor::Token> ShaderPreprocessor::tokenize(const std::string& code) const {
|
||||||
|
enum State {
|
||||||
|
FSlash,
|
||||||
|
WhiteSpace,
|
||||||
|
LineComment,
|
||||||
|
BlockComment,
|
||||||
|
BlockCommentEndStar,
|
||||||
|
Directive,
|
||||||
|
Token
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<ShaderPreprocessor::Token> tks;
|
||||||
|
|
||||||
|
std::string token = "";
|
||||||
|
State state = WhiteSpace;
|
||||||
|
for(char c : code) {
|
||||||
|
if (c==13) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
switch(state) {
|
||||||
|
case WhiteSpace:
|
||||||
|
if (c=='/') {
|
||||||
|
if (token != "") { tks.push_back({WS, token}); }
|
||||||
|
token = c;
|
||||||
|
state = FSlash;
|
||||||
|
} else if (c=='#') {
|
||||||
|
if (token != "") { tks.push_back({WS, token}); }
|
||||||
|
token = c;
|
||||||
|
state = Directive;
|
||||||
|
} else if (c=='\n') {
|
||||||
|
if (token != "") { tks.push_back({WS, token}); }
|
||||||
|
tks.push_back({NL, "\n"});
|
||||||
|
token = "";
|
||||||
|
state = WhiteSpace;
|
||||||
|
} else if (std::isblank(c)) {
|
||||||
|
token += c;
|
||||||
|
} else {
|
||||||
|
if (token != "") { tks.push_back({WS, token}); }
|
||||||
|
token = c;
|
||||||
|
state = Token;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case FSlash:
|
||||||
|
if (c=='/') {
|
||||||
|
token += c;
|
||||||
|
state = LineComment;
|
||||||
|
} else if (c=='*') {
|
||||||
|
token += c;
|
||||||
|
state = BlockComment;
|
||||||
|
} else if (c=='\n') {
|
||||||
|
tks.push_back({TK, token});
|
||||||
|
tks.push_back({NL, "\n"});
|
||||||
|
token = "";
|
||||||
|
state = WhiteSpace;
|
||||||
|
} else if (std::isblank(c)) {
|
||||||
|
tks.push_back({TK, token});
|
||||||
|
token = c;
|
||||||
|
}else {
|
||||||
|
token += c;
|
||||||
|
state = Token;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case LineComment:
|
||||||
|
if (c=='\n') {
|
||||||
|
tks.push_back({LC, token});
|
||||||
|
tks.push_back({NL, "\n"});
|
||||||
|
token = "";
|
||||||
|
state = WhiteSpace;
|
||||||
|
} else {
|
||||||
|
token += c;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case BlockComment:
|
||||||
|
token += c;
|
||||||
|
if (c=='*') {
|
||||||
|
state = BlockCommentEndStar;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case BlockCommentEndStar:
|
||||||
|
token += c;
|
||||||
|
if (c=='/') {
|
||||||
|
tks.push_back({BC, token});
|
||||||
|
token = "";
|
||||||
|
state = WhiteSpace;
|
||||||
|
} else {
|
||||||
|
state = BlockComment;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case Directive:
|
||||||
|
if (c=='\n') {
|
||||||
|
tks.push_back({DR, token});
|
||||||
|
tks.push_back({NL, "\n"});
|
||||||
|
token = "";
|
||||||
|
state = WhiteSpace;
|
||||||
|
} else if (c=='/') {
|
||||||
|
tks.push_back({DR, token});
|
||||||
|
token = c;
|
||||||
|
state = FSlash;
|
||||||
|
} else {
|
||||||
|
token += c;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case Token:
|
||||||
|
if (c=='\n') {
|
||||||
|
tks.push_back({TK, token});
|
||||||
|
tks.push_back({NL, "\n"});
|
||||||
|
token = "";
|
||||||
|
state = WhiteSpace;
|
||||||
|
} else if (std::isblank(c)) {
|
||||||
|
tks.push_back({TK, token});
|
||||||
|
token = c;
|
||||||
|
state = WhiteSpace;
|
||||||
|
} else if (c=='/') {
|
||||||
|
tks.push_back({TK, token});
|
||||||
|
token = c;
|
||||||
|
state = FSlash;
|
||||||
|
}else {
|
||||||
|
token += c;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
switch(state) {
|
||||||
|
case WhiteSpace:
|
||||||
|
if (token != "") { tks.push_back({WS, token}); }
|
||||||
|
case FSlash:
|
||||||
|
tks.push_back({TK, token});
|
||||||
|
break;
|
||||||
|
case LineComment:
|
||||||
|
tks.push_back({LC, token});
|
||||||
|
break;
|
||||||
|
case BlockComment:
|
||||||
|
case BlockCommentEndStar:
|
||||||
|
tks.push_back({BC, token});
|
||||||
|
break;
|
||||||
|
case Directive:
|
||||||
|
tks.push_back({DR, token});
|
||||||
|
break;
|
||||||
|
case Token:
|
||||||
|
tks.push_back({TK, token});
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tks;
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderUnit& ShaderPreprocessor::preprocess(const std::string& code, ShaderUnit& shad) const {
|
||||||
|
typedef ShaderPreprocessor::Token Token;
|
||||||
|
std::vector<Token> tks = tokenize(code);
|
||||||
|
|
||||||
|
for (int i{0}; i < tks.size(); ++i) {
|
||||||
|
switch(tks[i].first) {
|
||||||
|
case DR:
|
||||||
|
directive_dispatch(shad, tks[i].second);
|
||||||
|
break;
|
||||||
|
case TK:
|
||||||
|
case NL:
|
||||||
|
case LC:
|
||||||
|
case BC:
|
||||||
|
case WS:
|
||||||
|
default:
|
||||||
|
shad.preprocSource += tks[i].second;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shad.vMajor == 0 && shad.vMinor == 0) {
|
||||||
|
shad.vMajor = 1;
|
||||||
|
shad.vMinor = 10;
|
||||||
|
}
|
||||||
|
return shad;
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderUnit ShaderPreprocessor::preprocess(File file, GLenum shader_type) const {
|
||||||
|
ShaderUnit ret;
|
||||||
|
ret.file = file;
|
||||||
|
if (shader_type) {
|
||||||
|
ret.type = shader_type;
|
||||||
|
} else {
|
||||||
|
decltype(AcceptedExtensions.begin()) find_type = AcceptedExtensions.find(file.path.ext);
|
||||||
|
if (find_type != AcceptedExtensions.end()) {
|
||||||
|
ret.type = find_type->second;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
preprocess(file.src.str(), ret);
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderUnit ShaderPreprocessor::preprocess(const std::string& code, GLenum shader_type) const {
|
||||||
|
File local;
|
||||||
|
local.path = File::FilePath{"live:", "live", ".shad"};
|
||||||
|
return preprocess(local, shader_type);
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderProgram ShaderPreprocessor::CreateShaderProgram(std::vector<std::string> shads) const {
|
||||||
|
std::vector<ShaderUnit> _shader_units;
|
||||||
|
for (const auto& name : shads) {
|
||||||
|
_shader_units.push_back(preprocess(load(name)));
|
||||||
|
}
|
||||||
|
return ShaderProgram::CreateShaderProgram(_shader_units);
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderProgram ShaderPreprocessor::ReloadFromFile(const ShaderProgram& rhs) const {
|
||||||
|
std::vector<std::string> shader_names;
|
||||||
|
shader_names.reserve(rhs._shader_units.size());
|
||||||
|
std::string filename;
|
||||||
|
for (const ShaderUnit& shad : rhs._shader_units) {
|
||||||
|
filename = shad.file.path.dir + shad.file.path.basename + shad.file.path.ext;
|
||||||
|
shader_names.emplace_back(filename);
|
||||||
|
}
|
||||||
|
return CreateShaderProgram(shader_names);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderPreprocessor::directive_dispatch(ShaderUnit& shad, const std::string& line) const {
|
||||||
|
StringVec dir_tks = {""};
|
||||||
|
for (char c : line) {
|
||||||
|
if (std::isblank(c)) {
|
||||||
|
if (dir_tks.back() != "") {
|
||||||
|
dir_tks.push_back("");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dir_tks.back() += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!dir_tks.size()) { return false; }
|
||||||
|
|
||||||
|
if (dir_tks[0][0] != '#') { return false; }
|
||||||
|
|
||||||
|
if (dir_tks[0] == "#define") {
|
||||||
|
return preprocessor_define(shad, dir_tks, line);
|
||||||
|
} else if (dir_tks[0] == "#version") {
|
||||||
|
return preprocessor_version(shad, dir_tks, line);
|
||||||
|
} else if (dir_tks[0] == "#include") {
|
||||||
|
return preprocessor_include(shad, dir_tks, line);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef std::vector<std::string> StringVec;
|
||||||
|
|
||||||
|
bool ShaderPreprocessor::preprocessor_include(
|
||||||
|
ShaderUnit& shad,
|
||||||
|
const StringVec& tokens,
|
||||||
|
const std::string& line
|
||||||
|
) const
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
if (tokens[0] != "#include") { return false; }
|
||||||
|
} catch (std::out_of_range e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::string path = "";
|
||||||
|
for (const auto& tk : tokens) {
|
||||||
|
if (tk != tokens.front()) {
|
||||||
|
path += tk;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Add file-inclusion base +
|
||||||
|
// Do path cleanup +
|
||||||
|
// Restructure preprocessing data flow
|
||||||
|
std::string filename = path.substr(1, path.size()-2);
|
||||||
|
try {
|
||||||
|
if (path[0] == '"' && path.back() == '"') {
|
||||||
|
preprocess(load(filename).src.str(), shad);
|
||||||
|
return true;
|
||||||
|
} else if (path[0] == '<' && path.back() == '>') {
|
||||||
|
preprocess(load(filename, true).src.str(), shad);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch (ShaderPreprocessorError e) {
|
||||||
|
if (e.code == Codes::FILE_NOT_FOUND) {
|
||||||
|
std::cout << "COULD NOT FIND " << filename << ".\n";
|
||||||
|
} else {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderPreprocessor::preprocessor_define(ShaderUnit& shad, const StringVec& tokens, const std::string& line) const {
|
||||||
|
shad.preprocSource += line;
|
||||||
|
try {
|
||||||
|
if (tokens[0] != "#define") { return false; }
|
||||||
|
try {
|
||||||
|
shad.defines[tokens[1]] = tokens[2];
|
||||||
|
} catch (std::length_error& f) {
|
||||||
|
shad.defines[tokens[1]] = "";
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (std::out_of_range& e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ShaderPreprocessor::preprocessor_version(ShaderUnit& shad, const StringVec& tokens, const std::string& line) const {
|
||||||
|
shad.preprocSource += line;
|
||||||
|
std::cout << "Shader version: ";
|
||||||
|
try {
|
||||||
|
if (tokens[0] != "#version") { return false; }
|
||||||
|
if (tokens[1].size() == 3) {
|
||||||
|
short vMajor = tokens[1][0]-'0';
|
||||||
|
short vMinorA = tokens[1][1]-'0';
|
||||||
|
short vMinorB = tokens[1][2]-'0';
|
||||||
|
if (vMajor > 10 || vMinorA > 10 || vMinorB > 10) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
shad.vMajor = vMajor;
|
||||||
|
shad.vMinor = vMinorA*10 + vMinorB;
|
||||||
|
shad.profile = AcceptedProfiles.at(tokens[2]);
|
||||||
|
std::cout << shad.vMajor << "." << shad.vMinor << "\n";
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} catch (std::out_of_range& e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* bool ShaderPreprocessor::preprocessor_uniform(
|
||||||
|
ShaderUnit& shad,
|
||||||
|
const std::string& type,
|
||||||
|
const std::string& name
|
||||||
|
) const {
|
||||||
|
std::string type_str = "";
|
||||||
|
unsigned int type_str_len = 0;
|
||||||
|
for (const char& c : type) {
|
||||||
|
if (type_str_len) {
|
||||||
|
if (std::isdigit(c)) {
|
||||||
|
type_str += c;
|
||||||
|
continue;
|
||||||
|
} else if (c=='[') {
|
||||||
|
type_str += '_';
|
||||||
|
}else if (c == ']' || std::isblank(c)){
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (std::isalnum(c)) {
|
||||||
|
type_str += c;
|
||||||
|
continue;
|
||||||
|
} else if (c == '[') {
|
||||||
|
type_str_len = type_str.length();
|
||||||
|
type_str += '_';
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::string name_str = "";
|
||||||
|
unsigned int name_str_len = 0;
|
||||||
|
for (const char& c : name) {
|
||||||
|
if (c == ';') {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (name_str_len) {
|
||||||
|
if (std::isdigit(c)) {
|
||||||
|
type_str.insert(type_str_len, 1, c);
|
||||||
|
type_str_len++;
|
||||||
|
continue;
|
||||||
|
} else if (c=='[') {
|
||||||
|
type_str.insert(type_str_len, "_");
|
||||||
|
type_str_len++;
|
||||||
|
continue;
|
||||||
|
}else if (c == ']' || std::isblank(c)){
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (std::isalnum(c)) {
|
||||||
|
name_str += c;
|
||||||
|
continue;
|
||||||
|
} else if ( c == '[') {
|
||||||
|
name_str_len = name_str.length();
|
||||||
|
type_str.insert(type_str_len, "_");
|
||||||
|
type_str_len++;
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
shad.uniforms.push_back(UniformHandle{
|
||||||
|
name_str,
|
||||||
|
type_str,
|
||||||
|
0x0,
|
||||||
|
0x0
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} */
|
||||||
|
|
||||||
|
|
||||||
|
// ShaderProgram
|
||||||
|
|
||||||
|
ShaderProgram::ShaderProgram(ShaderProgram&& rhs) {
|
||||||
|
_shader_units = rhs._shader_units;
|
||||||
|
_id = rhs._id;
|
||||||
|
rhs._id = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderProgram::~ShaderProgram() {
|
||||||
|
glDeleteProgram(_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderProgram& ShaderProgram::operator=(ShaderProgram&& rhs) {
|
||||||
|
_shader_units = rhs._shader_units;
|
||||||
|
_id = rhs._id;
|
||||||
|
rhs._id = 0;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
ShaderProgram ShaderProgram::CreateShaderProgram(std::vector<ShaderUnit>& shaders) {
|
||||||
|
int success;
|
||||||
|
ShaderProgram ret(shaders);
|
||||||
|
char infoLog[512];
|
||||||
|
unsigned int shad_id;
|
||||||
|
std::vector<unsigned int> shad_ids;
|
||||||
|
shad_ids.reserve(shaders.size());
|
||||||
|
for (auto& shad : ret._shader_units) {
|
||||||
|
const char* source = shad.preprocSource.data();
|
||||||
|
shad_id = glCreateShader(shad.type);
|
||||||
|
shad_ids.emplace_back(shad_id);
|
||||||
|
glShaderSource(shad_id, 1, &source, NULL);
|
||||||
|
glCompileShader(shad_id);
|
||||||
|
glGetShaderiv(shad_id, GL_COMPILE_STATUS, &success);
|
||||||
|
if (!success) {
|
||||||
|
glGetShaderInfoLog(shad_id, 512, NULL, infoLog);
|
||||||
|
File::FilePath& fp = shad.file.path;
|
||||||
|
std::string filename = fp.dir + fp.basename + fp.ext;
|
||||||
|
// std::cout << "Could not compile '" + filename + "': " << infoLog << "\n";
|
||||||
|
// return *ret;
|
||||||
|
throw ShaderError("Could not compile '" + filename + "'.", infoLog);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ret._id = glCreateProgram();
|
||||||
|
for(auto& id : shad_ids) {
|
||||||
|
glAttachShader(ret._id, id);
|
||||||
|
}
|
||||||
|
glLinkProgram(ret._id);
|
||||||
|
glGetProgramiv(ret._id, GL_LINK_STATUS, &success);
|
||||||
|
if (!success) {
|
||||||
|
glGetProgramInfoLog(ret._id, 512, NULL, infoLog);
|
||||||
|
throw ShaderError("Could not link shader program.", infoLog);
|
||||||
|
}
|
||||||
|
for (auto& id : shad_ids) {
|
||||||
|
glDeleteShader(id);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int ShaderProgram::id() const { return _id; }
|
||||||
|
|
||||||
|
void ShaderProgram::use() const {
|
||||||
|
glUseProgram(_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<ShaderUnit> ShaderProgram::getShaders() const {
|
||||||
|
return _shader_units;
|
||||||
|
}
|
||||||
|
|
||||||
|
ShaderUnit ShaderProgram::getShaders(unsigned int idx) const {
|
||||||
|
return _shader_units[idx];
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderProgram::setBool(const std::string& name, bool value) const {
|
||||||
|
glUniform1i(glGetUniformLocation(_id, name.c_str()), (int)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderProgram::setInt(const std::string& name, int value) const {
|
||||||
|
glUniform1i(glGetUniformLocation(_id, name.c_str()), (int)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderProgram::setFloat(const std::string& name, float value) const {
|
||||||
|
glUniform1f(glGetUniformLocation(_id, name.c_str()), (int)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ShaderProgram::setMat4(const std::string& name, glm::mat4& value) const {
|
||||||
|
glUniformMatrix4fv(glGetUniformLocation(_id, name.c_str()), 1, GL_FALSE, glm::value_ptr(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* // Shader class
|
||||||
|
Shader::Shader() { _id = 0x0; }
|
||||||
|
|
||||||
|
Shader::Shader(const Shader& cpy_shader) { _id = cpy_shader._id; }
|
||||||
|
|
||||||
|
Shader& Shader::operator=(const Shader& cpy_shader) { _id = cpy_shader._id; return *this; }
|
||||||
|
|
||||||
|
void Shader::use() const{
|
||||||
|
glUseProgram(_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
cmake_minimum_required(VERSION 3.26.0)
|
|
||||||
|
|
||||||
if (NB_BUILD_TESTS)
|
|
||||||
enable_testing()
|
|
||||||
include(GoogleTest)
|
|
||||||
|
|
||||||
set(STBIMAGE_PATH ${NBENGINE_ROOT}/../stbi_image)
|
|
||||||
get_filename_component(STBIMAGE_PATH ${STBIMAGE_PATH} ABSOLUTE)
|
|
||||||
|
|
||||||
add_executable(TestWindow
|
|
||||||
./TestWindow.cpp
|
|
||||||
)
|
|
||||||
target_link_libraries(TestWindow
|
|
||||||
NBGraphics
|
|
||||||
)
|
|
||||||
target_include_directories(TestWindow
|
|
||||||
PRIVATE "${STBIMAGE_PATH}"
|
|
||||||
)
|
|
||||||
|
|
||||||
add_executable(TestImages
|
|
||||||
./testImages.cpp
|
|
||||||
)
|
|
||||||
target_link_libraries(TestImages
|
|
||||||
NBGraphics
|
|
||||||
GTest::gtest_main
|
|
||||||
)
|
|
||||||
target_include_directories(TestImages
|
|
||||||
PRIVATE "${STBIMAGE_PATH}"
|
|
||||||
)
|
|
||||||
|
|
||||||
gtest_discover_tests(TestImages)
|
|
||||||
|
|
||||||
endif()
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
#include <NBGraphics/GLLoad.hpp>
|
|
||||||
#define STB_IMAGE_IMPLEMENTATION
|
|
||||||
#include "stb_image.h"
|
|
||||||
|
|
||||||
#include <NBCore/Errors.hpp>
|
|
||||||
#include <NBGraphics/Image.hpp>
|
|
||||||
#include <NBGraphics/Mesh.hpp>
|
|
||||||
#include <NBGraphics/ProgramPipeline.hpp>
|
|
||||||
#include <NBGraphics/VertexData.hpp>
|
|
||||||
#include <NBGraphics/Window.hpp>
|
|
||||||
#include <NBGraphics/Textures.hpp>
|
|
||||||
|
|
||||||
|
|
||||||
int main() {
|
|
||||||
LOG("Howdy!");
|
|
||||||
auto window = nb::OGLWindow::CreateWindow(
|
|
||||||
400,
|
|
||||||
400,
|
|
||||||
"Howdy!",
|
|
||||||
{{GLFW_CONTEXT_VERSION_MAJOR, 3},
|
|
||||||
{GLFW_CONTEXT_VERSION_MINOR, 3}}
|
|
||||||
);
|
|
||||||
nb::OGLWindow::MakeCurrent(window);
|
|
||||||
|
|
||||||
auto vert = std::make_shared<nb::Shader>(
|
|
||||||
GL_VERTEX_SHADER,
|
|
||||||
"#version 330 core\n"
|
|
||||||
"layout (location = 0) in vec2 aPos;\n"
|
|
||||||
"out vec4 vColor;\n"
|
|
||||||
"void main()\n"
|
|
||||||
"{\n"
|
|
||||||
" gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);\n"
|
|
||||||
" vec2 tmp = (aPos+vec2(1.0, 1.0))*0.5;\n"
|
|
||||||
" vColor = vec4(tmp.x, 0, tmp.y, 1.0);\n"
|
|
||||||
"}\0"
|
|
||||||
);
|
|
||||||
|
|
||||||
LOG(vert->log());
|
|
||||||
|
|
||||||
auto frag = std::make_shared<nb::Shader>(
|
|
||||||
GL_FRAGMENT_SHADER,
|
|
||||||
"#version 330 core\n"
|
|
||||||
"in vec4 vColor;\n"
|
|
||||||
"out vec4 FragColor;\n"
|
|
||||||
"void main()\n"
|
|
||||||
"{\n"
|
|
||||||
" FragColor = vColor;\n"
|
|
||||||
"}\n\0"
|
|
||||||
);
|
|
||||||
|
|
||||||
LOG(frag->log());
|
|
||||||
|
|
||||||
nb::ByteVector data = nb::vectorToBytes<float>({
|
|
||||||
-0.5, -0.5,
|
|
||||||
0, 0.5,
|
|
||||||
0.5, -0.5
|
|
||||||
});
|
|
||||||
|
|
||||||
nb::Program prog({vert, frag});
|
|
||||||
prog.bind();
|
|
||||||
|
|
||||||
std::vector<uint32_t> indxs = {0, 1, 2};
|
|
||||||
|
|
||||||
nb::IndexedMesh tri(GL_TRIANGLES, data, {nb::VertexAttribute{
|
|
||||||
2,
|
|
||||||
nb::TypeCodes::FLOAT32,
|
|
||||||
false,
|
|
||||||
{0, 8}
|
|
||||||
}}, indxs);
|
|
||||||
LOG(prog.log());
|
|
||||||
|
|
||||||
using nb::WindowCallbacks;
|
|
||||||
|
|
||||||
window->setCallback<nb::KEY>(
|
|
||||||
[](nb::OGLWindow* w, int key, int, int, int)->void{
|
|
||||||
if (key == GLFW_KEY_Q) {
|
|
||||||
w->shouldClose(true);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
window->setCallback<nb::CURSOR_POS>(
|
|
||||||
[](nb::OGLWindow* w, double x, double y)->void{
|
|
||||||
nb::logger.msg("Pos in x is " + std::to_string(x));
|
|
||||||
}
|
|
||||||
);
|
|
||||||
while(!window->shouldClose()) {
|
|
||||||
OPENGL_CALL(glClearColor(0.2f, 0.3f, 0.3f, 1.0f));
|
|
||||||
OPENGL_CALL(glClear(GL_COLOR_BUFFER_BIT));
|
|
||||||
tri.draw();
|
|
||||||
window->pollEvents();
|
|
||||||
window->swapBuffers();
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 58 KiB |
@@ -1,156 +0,0 @@
|
|||||||
#include <gtest/gtest.h>
|
|
||||||
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#define STB_IMAGE_IMPLEMENTATION
|
|
||||||
#include "stb_image.h"
|
|
||||||
|
|
||||||
#include <NBGraphics/Image.hpp>
|
|
||||||
|
|
||||||
TEST(TestImage, SinglePixel) {
|
|
||||||
using RGB = nb::Pixel<uint8_t, nb::Red, nb::Green, nb::Blue>;
|
|
||||||
RGB p1;
|
|
||||||
p1.r = 0x00;
|
|
||||||
p1.g = 0x0F;
|
|
||||||
p1.b = 0xFF;
|
|
||||||
ASSERT_EQ(p1.r, 0x00);
|
|
||||||
ASSERT_EQ(p1.g, 0x0F);
|
|
||||||
ASSERT_EQ(p1.b, 0xFF);
|
|
||||||
RGB p2(p1);
|
|
||||||
ASSERT_EQ(p2.r, 0x00);
|
|
||||||
ASSERT_EQ(p2.g, 0x0F);
|
|
||||||
ASSERT_EQ(p2.b, 0xFF);
|
|
||||||
RGB p3(0xA, 0xB, 0xC);
|
|
||||||
ASSERT_EQ(p3.r, 0xA);
|
|
||||||
ASSERT_EQ(p3.g, 0xB);
|
|
||||||
ASSERT_EQ(p3.b, 0xC);
|
|
||||||
RGB p4 = p3;
|
|
||||||
ASSERT_EQ(p4.r, 0xA);
|
|
||||||
ASSERT_EQ(p4.g, 0xB);
|
|
||||||
ASSERT_EQ(p4.b, 0xC);
|
|
||||||
RGB p5(0xA0, 0xB0, 0xC0);
|
|
||||||
ASSERT_EQ(p5.r, 0xA0);
|
|
||||||
ASSERT_EQ(p5.g, 0xB0);
|
|
||||||
ASSERT_EQ(p5.b, 0xC0);
|
|
||||||
|
|
||||||
using RBAG = nb::Pixel<float,
|
|
||||||
nb::Red, nb::Blue, nb::Alpha, nb::Green
|
|
||||||
>;
|
|
||||||
float a=0.5, b=0.4, c=0.0, d=0.3;
|
|
||||||
RBAG p6 = {a, b, c, d};
|
|
||||||
ASSERT_EQ(p6.r, a);
|
|
||||||
ASSERT_EQ(p6.b, b);
|
|
||||||
ASSERT_EQ(p6.a, c);
|
|
||||||
ASSERT_EQ(p6.g, d);
|
|
||||||
RBAG p7 = p6;
|
|
||||||
ASSERT_EQ(p7.r, a);
|
|
||||||
ASSERT_EQ(p7.b, b);
|
|
||||||
ASSERT_EQ(p7.a, c);
|
|
||||||
ASSERT_EQ(p7.g, d);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(TestImage, PixelReference) {
|
|
||||||
using RGB = nb::Pixel<uint8_t, nb::Red, nb::Green, nb::Blue>;
|
|
||||||
using RGBRef = nb::PixelReference<RGB>;
|
|
||||||
|
|
||||||
using RBAG = nb::Pixel<float,
|
|
||||||
nb::Red, nb::Blue, nb::Alpha, nb::Green
|
|
||||||
>;
|
|
||||||
using RBAGRef = nb::PixelReference<RBAG>;
|
|
||||||
|
|
||||||
RGB p1{255, 254, 253};
|
|
||||||
RGBRef rp1(p1);
|
|
||||||
ASSERT_EQ(rp1.r, p1.r);
|
|
||||||
ASSERT_EQ(rp1.g, p1.g);
|
|
||||||
ASSERT_EQ(rp1.b, p1.b);
|
|
||||||
|
|
||||||
RGB p2{0xa, 0xb, 0xc};
|
|
||||||
rp1 = p2;
|
|
||||||
ASSERT_EQ(p1.r, p2.r);
|
|
||||||
ASSERT_EQ(p1.g, p2.g);
|
|
||||||
ASSERT_EQ(p1.b, p2.b);
|
|
||||||
|
|
||||||
RGB p3 = rp1;
|
|
||||||
ASSERT_EQ(p3.r, p1.r);
|
|
||||||
ASSERT_EQ(p3.g, p1.g);
|
|
||||||
ASSERT_EQ(p3.b, p1.b);
|
|
||||||
|
|
||||||
RGBRef rp2 = rp1;
|
|
||||||
rp2 = RGB(2, 4, 8);
|
|
||||||
ASSERT_EQ(p1.r, 2);
|
|
||||||
ASSERT_EQ(p1.g, 4);
|
|
||||||
ASSERT_EQ(p1.b, 8);
|
|
||||||
|
|
||||||
int val = 27;
|
|
||||||
rp1.b = val;
|
|
||||||
ASSERT_EQ(rp1.r, p1.r);
|
|
||||||
ASSERT_EQ(rp1.g, p1.g);
|
|
||||||
ASSERT_EQ(rp1.b, p1.b);
|
|
||||||
ASSERT_EQ(p1.b, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(TestImage, SimpleImage) {
|
|
||||||
unsigned char data[] = {
|
|
||||||
0x00, 0x00,
|
|
||||||
0x00, 0xFF,
|
|
||||||
0xFF, 0x00,
|
|
||||||
0xFF, 0xFF
|
|
||||||
};
|
|
||||||
using RG = nb::Pixel<uint8_t, nb::Red, nb::Blue>;
|
|
||||||
nb::Image<RG> img(
|
|
||||||
2, 2, data
|
|
||||||
);
|
|
||||||
for (int i = 0; i < sizeof(data); ++i) {
|
|
||||||
ASSERT_EQ(img.data()[i], data[i]);
|
|
||||||
}
|
|
||||||
auto pixel = img.at(0, 1);
|
|
||||||
ASSERT_EQ(pixel.r, data[4]);
|
|
||||||
ASSERT_EQ(pixel.b, data[5]);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(TestImage, LoadImage) {
|
|
||||||
int width, height, numChannels;
|
|
||||||
unsigned char* data = stbi_load(
|
|
||||||
"./awesomeface.png",
|
|
||||||
&width,
|
|
||||||
&height,
|
|
||||||
&numChannels,
|
|
||||||
0
|
|
||||||
);
|
|
||||||
using RGBA = nb::Pixel<unsigned char, nb::Red, nb::Green, nb::Blue, nb::Alpha>;
|
|
||||||
nb::Image<RGBA> img(
|
|
||||||
width, height, data
|
|
||||||
);
|
|
||||||
for(int i = 0; i < height; ++i) {
|
|
||||||
for (int j = 0; j < width; ++j) {
|
|
||||||
auto pixel = img.at(j, i);
|
|
||||||
ASSERT_EQ(pixel.r, data[4*(i*width+j)]);
|
|
||||||
ASSERT_EQ(pixel.g, data[4*(i*width+j) + 1]);
|
|
||||||
ASSERT_EQ(pixel.b, data[4*(i*width+j) + 2]);
|
|
||||||
ASSERT_EQ(pixel.a, data[4*(i*width+j) + 3]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
stbi_image_free(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST(TestImage, ImageBounds) {
|
|
||||||
size_t len = 10;
|
|
||||||
uint8_t val = 0xAA;
|
|
||||||
std::vector<uint8_t> vec(2*len*len, val);
|
|
||||||
using RB = nb::Pixel<uint8_t, nb::Red, nb::Blue>;
|
|
||||||
nb::Image<RB> img(
|
|
||||||
len, len, vec.data()
|
|
||||||
);
|
|
||||||
for (int i=0; i < 15; ++i) {
|
|
||||||
if (i<len) {
|
|
||||||
auto pixel = img.at(len/2, i);
|
|
||||||
ASSERT_EQ(pixel.r, val);
|
|
||||||
ASSERT_EQ(pixel.b, val);
|
|
||||||
} else {
|
|
||||||
ASSERT_THROW(img.at(len/2, i), nb::ImageError);
|
|
||||||
ASSERT_THROW(img.at(i, len/2), nb::ImageError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user