24 Commits
Author SHA1 Message Date
NaifBanana 97aed4e5ca Honestly fuck if i know atp 2026-10-19 03:09:35 -05:00
NaifBanana 416446206f Made window hinting/param system easier 2026-10-12 16:54:36 -05:00
NaifBanana c6ab0327c1 Removed include functional 2026-10-12 00:52:24 -05:00
NaifBanana e6a5c9e805 Better callbacks 2026-10-12 00:51:50 -05:00
NaifBanana b9e8144519 Added callbacks 2026-10-11 17:48:27 -05:00
NaifBanana 06f261b793 Heavy buffer update, window update, object tracking 2026-10-11 13:32:47 -05:00
NaifBanana e76ef32c45 Nuked old window class outta orbit! 2026-10-11 13:32:47 -05:00
NaifBanana f49650744a Lots of stuff, ending with Window restruct 2026-10-11 13:32:47 -05:00
NaifBanana ab56a2cc95 Minor cleanup and added some Type utils 2026-10-11 13:32:27 -05:00
NaifBanana e2ea8c5373 Added tid global tools 2026-09-09 12:15:41 -05:00
NaifBanana be68245771 Uhhhhh big big changes 2026-08-20 08:14:29 -05:00
NaifBanana bb2f046c90 Made NBGraphics installable 2026-08-20 08:14:29 -05:00
NaifBanana 3bad580793 Huge graphics overhaul 2026-08-20 08:14:29 -05:00
NaifBanana 960689ecb6 Forgot to actually compile the shader :P 2026-08-20 08:14:29 -05:00
NaifBanana a5c207d150 Change invalid buffer binding to warning instead of error 2026-08-20 08:14:28 -05:00
NaifBanana ecd6db5eab Added vertex buffers/data handling and shader/program handling 2026-08-20 08:14:28 -05:00
NaifBanana 52a01debd6 Mild updates to Window and other pieces to match the rest 2026-08-20 08:14:28 -05:00
NaifBanana fa749a6ebf Make VertexAttributePointer store index instead of buffer pointer 2026-08-20 08:14:28 -05:00
NaifBanana cac2eca144 Made buildable now 2026-08-20 08:14:28 -05:00
NaifBanana 3a097df594 Large OpenGL Object handling overhaul 2026-08-20 08:14:28 -05:00
NaifBanana bfe020c5c6 Initial NBData, added FFT 2026-08-20 08:11:13 -05:00
NaifBanana 91cdfc1754 Merge branch 'main' of https://git.naifb.com/naifb/NBEngine 2026-08-20 08:10:29 -05:00
NaifBanana 9628a75710 Better sinks, better loggers, etx 2026-08-20 08:08:20 -05:00
naifb 352a45bce0 Update README.md 2026-06-26 14:54:17 +00:00
57 changed files with 2681 additions and 1903 deletions
+4 -2
View File
@@ -1,8 +1,10 @@
build/ build/
.vscode/ .*
!.gitignore
!.clangd
CMakeFiles/ CMakeFiles/
CMakeKits.json
CMakeCache.txt CMakeCache.txt
docs/* docs/*
!docs/CMake* !docs/CMake*
!docs/Doxyfile.in !docs/Doxyfile.in
!.clangd
+42 -23
View File
@@ -9,6 +9,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
include(GNUInstallDirs) include(GNUInstallDirs)
include(CMakePackageConfigHelpers) include(CMakePackageConfigHelpers)
include(CMakeDependentOption)
function(toAbsolutePath SETVAR PATHS) function(toAbsolutePath SETVAR PATHS)
set(PATHS ${PATHS} ${ARGN}) set(PATHS ${PATHS} ${ARGN})
@@ -27,16 +28,32 @@ function(toAbsolutePath SETVAR PATHS)
set(${SETVAR} ${RET_VAL} PARENT_SCOPE) set(${SETVAR} ${RET_VAL} PARENT_SCOPE)
endfunction() endfunction()
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Debug")
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Release") if(CMAKE_BUILD_TYPE STREQUAL "Release")
message(STATUS "Targeting Release build") add_compile_definitions(_NB_BUILD_RELEASE)
elseif(CMAKE_BUILD_TYPE STREQUAL "Debug") elseif(CMAKE_BUILD_TYPE STREQUAL "Debug")
message(STATUS "Targeting Debug build") set(NB_DEBUG_BUILD ON)
set(NB_LOGGING ON)
set(NB_BUILD_TESTS ON)
set(NB_BUILD_DOCS ON)
set(NBENGINE_INSTALL ON)
add_compile_definitions(_NB_BUILD_DEBUG) add_compile_definitions(_NB_BUILD_DEBUG)
endif() endif()
message(STATUS "Targeting ${CMAKE_BUILD_TYPE} build")
if (NB_DEBUG_BUILD)
set(NB_LOGGING ON)
set(NB_BUILD_TESTS ON)
set(NB_BUILD_DOCS ON)
set(NB_MONITOR_OPENGL_CALLS ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS 1)
endif()
cmake_dependent_option(NBENGINE_INSTALL
"Install NBEngine"
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")
@@ -67,13 +84,14 @@ if (NB_LOGGING)
add_compile_definitions(_NB_CODE_ERROR_LOCATIONS) 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)
elseif (NB_TARGET_LINUX) endif()
if(NB_TARGET_LINUX)
add_compile_definitions(_NB_TARGET_LINUX) add_compile_definitions(_NB_TARGET_LINUX)
endif() endif()
get_filename_component(NBENGINE_ROOT ./ ABSOLUTE) get_filename_component(NBENGINE_ROOT ${CMAKE_CURRENT_LIST_DIR} ABSOLUTE)
add_subdirectory(./engine) add_subdirectory(./engine)
@@ -81,25 +99,26 @@ add_subdirectory(./engine)
set(NB_REBUILD_DOCS) 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) if (NBENGINE_INSTALL)
include(GNUInstallDirs) include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
configure_package_config_file(
"NBEngineConfig.cmake.in"
"NBEngineConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
PATH_VARS CMAKE_INSTALL_LIBDIR
)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/NBEngineConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion
)
install(FILES install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/NBEngineConfig.cmake" "${PROJECT_BINARY_DIR}/cmake/NBEngineConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/NBEngineConfigVersion.cmake" "${PROJECT_BINARY_DIR}/cmake/NBEngineConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake" DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
) )
endif() endif()
+3
View File
@@ -4,6 +4,9 @@
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.
+16 -5
View File
@@ -3,17 +3,28 @@ add_subdirectory(./NBCore)
get_target_property(NBCORE_INTERFACE_INCLUDES NBCore INTERFACE_INCLUDE_DIRECTORIES) get_target_property(NBCORE_INTERFACE_INCLUDES NBCore INTERFACE_INCLUDE_DIRECTORIES)
include_directories(${NBCORE_INTERFACE_INCLUDES}) include_directories(${NBCORE_INTERFACE_INCLUDES})
add_subdirectory(./NBEvents) #add_subdirectory(./NBEvents)
add_subdirectory(./NBGraphics) add_subdirectory(./NBGraphics)
add_subdirectory(./NBData)
if (NB_CORE_SOURCE OR NB_EVENTS_SOURCE OR NB_GRAPHICS_SOURCE) if (NB_CORE_SOURCE OR NB_EVENTS_SOURCE OR NB_GRAPHICS_SOURCE OR NB_DATA_SOURCE)
set(NB_SOURCE_FILES "") set(NB_SOURCE_FILES "")
list(APPEND NB_SOURCE_FILES ${NB_CORE_SOURCE} ${NB_GRAPHICS_SOURCE} ${NB_EVENTS_SOURCE}) list(APPEND NB_SOURCE_FILES
${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) if (NB_CORE_INCLUDE OR NB_EVENTS_INCLUDE OR NB_GRAPHICS_INCLUDE OR NB_DATA_INCLUDE)
set(NB_INCLUDE_FILES "") set(NB_INCLUDE_FILES "")
list(APPEND NB_INCLUDE_FILES ${NB_CORE_INCLUDE} ${NB_GRAPHICS_INCLUDE} ${NB_EVENTS_INCLUDE}) list(APPEND NB_INCLUDE_FILES
${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()
+36 -21
View File
@@ -1,19 +1,28 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(NBCore VERSION 0.1) 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/ErrorsImpl.cpp
./src/Logger.cpp ./src/Logger.cpp
./src/Processes.cpp ./src/Processes.cpp
./src/StringUtils.cpp ./src/StringUtils.cpp
./src/TypeTraits.cpp
./src/Utils.cpp ./src/Utils.cpp
) )
toAbsolutePath(NB_CORE_INCLUDE toAbsolutePath(NB_CORE_INCLUDE
./include/NBCore/ANSITerm.hpp
./include/NBCore/DataSink.hpp ./include/NBCore/DataSink.hpp
./include/NBCore/Errors.hpp ./include/NBCore/DataTypes.hpp
./include/NBCore/Errors.hpp
./include/NBCore/ErrorsImpl.hpp ./include/NBCore/ErrorsImpl.hpp
./include/NBCore/Logger.hpp ./include/NBCore/Logger.hpp
./include/NBCore/Printer.hpp
./include/NBCore/Processes.hpp ./include/NBCore/Processes.hpp
./include/NBCore/StringUtils.hpp ./include/NBCore/StringUtils.hpp
./include/NBCore/ThreadsafeQueue.hpp ./include/NBCore/ThreadsafeQueue.hpp
@@ -28,45 +37,51 @@ 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) add_library(NBEngine::Core ALIAS NBCore)
target_include_directories(NBCore target_include_directories(NBCore
PUBLIC "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>" PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" 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) if (NBENGINE_INSTALL)
message("Installing NBCore to ${CMAKE_INSTALL_PREFIX}") message("Installing NBCore to ${CMAKE_INSTALL_PREFIX}")
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
install( install(
TARGETS NBCore TARGETS NBCore
EXPORT NBCoreTargets EXPORT NBCoreTargets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
INCLUDES DESTINATION include
) )
install( install(
DIRECTORY "${PROJECT_SOURCE_DIR}/include/NBCore" DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/NBCore"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp" FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
) )
install( install(
EXPORT NBCoreTargets EXPORT NBCoreTargets
DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake"
NAMESPACE NBEngine:: NAMESPACE NBEngine::
) )
configure_package_config_file(
"NBCoreConfig.cmake.in"
"NBCoreConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
PATH_VARS CMAKE_INSTALL_LIBDIR
)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/NBCoreConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion
)
install(FILES install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/NBCoreConfig.cmake" "${CMAKE_BINARY_DIR}/cmake/NBCoreConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/NBCoreConfigVersion.cmake" "${CMAKE_BINARY_DIR}/cmake/NBCoreConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake" DESTINATION "${CMAKE_INSTALL_PREFIX}/CMake"
) )
endif() endif()
if (NB_BUILD_TESTS) if (NB_BUILD_TESTS)
add_subdirectory(./tests) add_subdirectory(./tests )
endif() endif()
-214
View File
@@ -1,214 +0,0 @@
#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
+123 -73
View File
@@ -4,6 +4,7 @@
#include <atomic> #include <atomic>
#include <thread> #include <thread>
#include <utility>
#include <NBCore/ThreadSafeQueue.hpp> #include <NBCore/ThreadSafeQueue.hpp>
@@ -11,121 +12,170 @@ namespace nb {
template<typename DataType> template<typename DataType>
class DataSink { class DataSink {
public: public:
DataSink(const DataSink&) = delete; DataSink(const DataSink&) = delete;
DataSink(DataSink&&) = delete; DataSink(DataSink&&) = delete;
DataSink& operator=(const DataSink&) = delete; DataSink& operator=(const DataSink&) = delete;
virtual bool isRunning() const noexcept { virtual bool isRunning() const noexcept {
return _running; std::atomic_thread_fence(std::memory_order_acquire);
return _running.load(std::memory_order_acquire);
} }
virtual bool stop() noexcept = 0; virtual bool stop() noexcept = 0;
virtual bool run() = 0; virtual bool run() = 0;
virtual bool in(const DataType&) = 0; virtual bool in(const DataType&) = 0;
protected: protected:
DataSink() = default; DataSink() {
_running.store(false, std::memory_order_release);
}
std::atomic<bool> _running; 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> template<typename DataType, typename BufferType, typename ProcessorType>
class BufferedDataProcessor : public DataSink<DataType> { class BufferedDataProcessor : public DataSink<DataType> {
using Base = DataSink<DataType>; private:
public: ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
using Base::Base;
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 stop() noexcept override { return type_ptr->stop(); }
virtual bool run() override { return type_ptr->run(); } virtual bool run() override { return type_ptr->run(); }
virtual bool in(const DataType& val) override { return type_ptr->in(val); } virtual bool in(const DataType& val) override { 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> template<typename DataType, typename ProcessorType>
class MultithreadedDataProcessor class MultithreadedDataProcessor
: public BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType> { : public BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType> {
using Base = BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType>; private:
public: ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
~MultithreadedDataProcessor() { type_ptr->stop(); } std::mutex _pause;
bool isRunning() const noexcept override { protected:
return this->_running; 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 { bool run() override {
if (!type_ptr->isRunning()) { if (!type_ptr->isRunning()) {
this->_running = true; _running.store(true, std::memory_order_release);
_runningThread = std::make_shared<std::thread>([&]{ _runningThread = std::make_shared<std::thread>([&]{
while(type_ptr->isRunning()) { while(type_ptr->isRunning()) {
flush(); std::lock_guard<std::mutex> lock(_pause);
type_ptr->flush();
} }
type_ptr->flush();
type_ptr->stop();
}); });
} }
return this->isRunning(); return type_ptr->isRunning();
} }
bool stop() noexcept override { bool stop() noexcept override {
if (type_ptr->isRunning()) { if (type_ptr->isRunning()) {
this->_running = false; _running.store(false, std::memory_order_release);
_runningThread->join(); if (_runningThread) {
_runningThread = nullptr; _runningThread->join();
_runningThread = nullptr;
}
type_ptr->flush();
} }
return !type_ptr->isRunning(); return !type_ptr->isRunning();
} }
bool in(const DataType& val) override {
protected: type_ptr->_buffer.push(val);
using Base::Base; return type_ptr->isRunning();
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);
}; };
@@ -0,0 +1,71 @@
#pragma once
#include <cstring>
#ifndef _NB_DATA_TYPES
#define _NB_DATA_TYPES
#include <algorithm>
#include <array>
#include <memory>
namespace nb {
template<typename T, unsigned int N>
class NDArray {
protected:
std::unique_ptr<T[]> _data;
static unsigned int calculateTotalSize(const std::array<unsigned int, N>& dims) {
unsigned int ret = 1;
std::for_each(dims.begin(), dims.end(), [&](unsigned int n){
ret *= n;
});
return ret;
}
public:
const std::array<unsigned int, N> dimensions;
const unsigned int totalSize;
static constexpr unsigned int NumberDimensions = N;
NDArray(
const std::array<unsigned int, N>& dimensions_,
T* data_=nullptr
) :
dimensions(dimensions_),
totalSize(calculateTotalSize(dimensions_))
{
if (data_) { data(data_); }
}
NDArray(
const std::array<unsigned int, N>& dimensions_,
const T* data_
) : NDArray(dimensions_) { data(data_); }
unsigned int coordinateToIndex(const std::array<T, N>& coord) const {
unsigned int blockSize = 1;
unsigned int ret = 0;
for (auto i = 0; i < dimensions.size(); ++i) {
ret += coord[i] * blockSize;
blockSize *= dimensions[i];
}
return ret;
}
inline const T& at(const std::array<T, N>& coord) const {
return _data[coordinateToIndex(coord)];
}
inline std::shared_ptr<T> data() const { return _data; }
inline T& at(const std::array<T, N>& coord) {
return _data[coordinateToIndex(coord)];
}
inline T* data(const T* data_) {
_data = std::make_unique<T[]>(totalSize);
std::memcpy(_data.get(), data_, totalSize * sizeof(T));
return _data.get();
}
}; // namespace nb
}
#endif // _NB_DATA_TYPES
+29 -7
View File
@@ -8,35 +8,57 @@
namespace nb { namespace nb {
#ifdef _NB_AUTOLOG #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 #ifdef _NB_CODE_ERROR_LOCATIONS
#ifndef LOG #ifndef LOG
#define LOG(args...) nb::logger.log(args, __FILE__, __LINE__) #define LOG(arg) LOG_W_CODE_LOC(__FILE__, __LINE__, arg)
#endif // LOG #endif // LOG
#ifndef WARN #ifndef WARN
#define WARN(args...) nb::logger.warn(args, __FILE__, __LINE__) #define WARN(args...) WARN_W_CODE_LOC(__FILE__, __LINE__, args)
#endif // WARN #endif // WARN
#ifndef ERROR #ifndef ERROR
#define ERROR(args...) nb::logger.error(args, __FILE__, __LINE__) #define ERROR(arg) ERROR_W_CODE_LOC(__FILE__, __LINE__, arg)
#endif // ERROR #endif // ERROR
#else #else
#ifndef LOG #ifndef LOG
#define LOG(args...) nb::logger.log(args) #define LOG(args) nb::logger.msg(args)
#endif // LOG #endif // LOG
#ifndef WARN #ifndef WARN
#define WARN(args...) nb::logger.warn(args) #define WARN(args...) nb::logger.warn(args)
#endif // WARN #endif // WARN
#ifndef ERROR #ifndef ERROR
#define ERROR(args...) nb::logger.error(args) #define ERROR(args) nb::logger.error(args)
#endif // ERROR #endif // ERROR
#endif // _NB_CODE_ERROR_LOCATIONS #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 #endif // _NB_AUTOLOG
#ifndef THROW #ifndef THROW
#ifdef _NB_AUTOLOG #ifdef _NB_AUTOLOG
#define THROW(args...) ERROR(args); nb::logger.stop(); throw args #define THROW(args...) THROW_W_CODE_LOC(__FILE__, __LINE__, args)
#else #else
#define THROW(args...) throw args #define THROW(args...) throw args
#endif // _NB_CODE_ERROR_LOCATIONS #endif // _NB_AUTOLOG
#endif // THROW #endif // THROW
} // namespace nb } // namespace nb
+26 -31
View File
@@ -6,13 +6,13 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <type_traits> #include <type_traits>
#include <unordered_map>
#include <NBCore/StringUtils.hpp> #include <NBCore/StringUtils.hpp>
#include <NBCore/Utils.hpp>
namespace nb { namespace nb {
typedef std::unordered_map<unsigned int, std::string> ErrorCodeMap; using ErrorCodeMap = ConstantMap<unsigned int, std::string>;
class ErrorBase { class ErrorBase {
protected: protected:
@@ -25,11 +25,10 @@ class ErrorBase {
ErrorBase(const ErrorBase&) = default; ErrorBase(const ErrorBase&) = default;
ErrorBase(const std::exception&) noexcept; ErrorBase(const std::exception&) noexcept;
ErrorBase(const std::string&) noexcept;
virtual std::string what() const noexcept { virtual std::string what() const noexcept {
std::string ret = msg; std::string ret = msg;
if (trace) { if (trace) {
std::string trace_msg = msg; std::string trace_msg = trace->what();
ret += NEWLINE + indent_strblock( ret += NEWLINE + indent_strblock(
trace_msg, trace_msg,
TABOVER, TABOVER,
@@ -41,16 +40,16 @@ class ErrorBase {
protected: protected:
ErrorBase( ErrorBase(
unsigned int code_, unsigned int code_,
std::string msg_, std::string msg_,
std::string type_, std::string type_,
std::shared_ptr<ErrorBase> trace_ std::shared_ptr<ErrorBase> trace_
) noexcept : ) noexcept :
code(code_), code(code_),
msg(msg_), msg(msg_),
type(type_), type(type_),
trace{trace_} trace{trace_}
{} {}
}; };
template <class ErrorType=NoneType> template <class ErrorType=NoneType>
@@ -70,16 +69,15 @@ class Error : public ErrorBase {
); );
} }
protected: public:
using ErrorBase::ErrorBase; using ErrorBase::ErrorBase;
public:
Error( Error(
unsigned int code_, unsigned int code_,
const ErrorBase& trace_ const ErrorBase& trace_
) noexcept : ErrorBase( ) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_), ErrorType::ErrorMessages[code_],
ErrorType::type, ErrorType::type,
std::make_shared<ErrorBase>(trace_) std::make_shared<ErrorBase>(trace_)
) { check_asserts(); } ) { check_asserts(); }
@@ -88,7 +86,7 @@ class Error : public ErrorBase {
std::string msg_, std::string msg_,
const ErrorBase& trace_ const ErrorBase& trace_
) noexcept : ErrorBase( ) noexcept : ErrorBase(
0, ErrorType::Codes::UNDEFINED,
msg_, msg_,
ErrorType::type, ErrorType::type,
std::make_shared<ErrorBase>(trace_) std::make_shared<ErrorBase>(trace_)
@@ -96,13 +94,13 @@ class Error : public ErrorBase {
Error(unsigned int code_) noexcept : ErrorBase( Error(unsigned int code_) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_), ErrorType::ErrorMessages[code_],
ErrorType::type, ErrorType::type,
nullptr nullptr
) { check_asserts(); } ) { check_asserts(); }
Error(std::string msg_) noexcept : ErrorBase( Error(std::string msg_) noexcept : ErrorBase(
0, ErrorType::Codes::UNDEFINED,
msg_, msg_,
ErrorType::type, ErrorType::type,
nullptr nullptr
@@ -114,14 +112,14 @@ class Error : public ErrorBase {
const ErrorBase& trace_ const ErrorBase& trace_
) noexcept : ErrorBase( ) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_) + " (" + note_ + ")", ErrorType::ErrorMessages[code_] + " (" + note_ + ")",
ErrorType::type, ErrorType::type,
std::make_shared<ErrorBase>(trace_) std::make_shared<ErrorBase>(trace_)
) { check_asserts(); } ) { check_asserts(); }
Error(unsigned int code_, const std::string& note_) noexcept : ErrorBase( Error(unsigned int code_, const std::string& note_) noexcept : ErrorBase(
code_, code_,
ErrorType::ErrorMessages.at(code_) + " (" + note_ + ")", ErrorType::ErrorMessages[code_] + " (" + note_ + ")",
ErrorType::type, ErrorType::type,
nullptr nullptr
) { check_asserts(); } ) { check_asserts(); }
@@ -142,14 +140,18 @@ class Error<NoneType> : public Error<Error<NoneType>> {
using Base::what; using Base::what;
using Base::code; using Base::code;
using Base::trace; using Base::trace;
using Base::Base;
enum Codes : unsigned int { enum Codes : unsigned int {
STANDARD, UNDEFINED, INDEX_ERROR STANDARD, UNDEFINED, OUT_OF_RANGE, VALUE_ERROR, OVERWRITE_ERROR
}; };
inline static const std::string type = "nb::Error"; inline static const std::string type = "nb::Error";
inline static const ErrorCodeMap ErrorMessages = { inline static const ErrorCodeMap ErrorMessages = {
{STANDARD, "std::exception"}, {STANDARD, "std::exception"},
{UNDEFINED, "Error"}, {UNDEFINED, "Error"},
{INDEX_ERROR, "Indexing 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(unsigned int code_=1) noexcept : Base(code_) {}
@@ -159,13 +161,6 @@ class Error<NoneType> : public Error<Error<NoneType>> {
"std::exception", "std::exception",
nullptr nullptr
) {} ) {}
Error(const std::string& msg_) noexcept : Base(
Codes::UNDEFINED,
msg_,
type,
nullptr
) {}
}; };
template<typename... Args> template<typename... Args>
+146 -89
View File
@@ -3,13 +3,13 @@
#define _NB_LOGGER #define _NB_LOGGER
#include <chrono> #include <chrono>
#include <ostream>
#include <thread> #include <thread>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <NBCore/DataSink.hpp> #include <NBCore/DataSink.hpp>
#include <NBCore/ErrorsImpl.hpp> #include <NBCore/ErrorsImpl.hpp>
#include <NBCore/Printer.hpp>
#include <NBCore/Processes.hpp> #include <NBCore/Processes.hpp>
#include <NBCore/ThreadSafeQueue.hpp> #include <NBCore/ThreadSafeQueue.hpp>
#include <NBCore/TypeTraits.hpp> #include <NBCore/TypeTraits.hpp>
@@ -26,32 +26,32 @@ typedef std::chrono::time_point<
typedef std::string (*LogProcessFunction)(const LoggerTimePoint&, const std::string&); typedef std::string (*LogProcessFunction)(const LoggerTimePoint&, const std::string&);
typedef std::unordered_map<uint8_t, LogProcessFunction> LogProcessFunctionMap; typedef std::unordered_map<uint8_t, LogProcessFunction> LogProcessFunctionMap;
template<typename LogType, typename Logger, typename ST=std::ostream*> template<typename LogType, typename Logger>
class LoggerBase class LoggerBase : public MultithreadedDataProcessor<LogType, Logger>{
: public MultithreadedDataProcessor<LogType, Logger>{ private:
using StreamType = ST; Logger* const type_ptr = static_cast<LoggerType*>(this);
using LoggerType = Logger;
using Base = MultithreadedDataProcessor<LogType, LoggerType>;
public:
bool run() override {
if (!static_cast<LoggerType*>(this)->isRunning()) {
this->_running = true;
this->_runningThread = std::make_shared<std::thread>([&]{
while(static_cast<LoggerType*>(this)->isRunning()) {
static_cast<LoggerType*>(this)->flush();
}
static_cast<LoggerType*>(this)->flush();
});
}
return static_cast<LoggerType*>(this)->isRunning();
}
using Base::flush;
protected: protected:
LoggerBase() = default; 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;
}
StreamType _ostream;
}; };
struct LogEvent{ struct LogEvent{
@@ -64,59 +64,42 @@ struct LogEvent{
const unsigned int line=0; 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> template <typename LT>
class DebugLogger : public LoggerBase<LogEvent, LT, std::vector<std::ostream*>>{ class DebugLogger : public LoggerBase<LogEvent, LT>{
using StreamType = std::vector<std::ostream*>; private:
using LoggerType = LT; LT* const type_ptr = static_cast<LT*>(this);
using Base = LoggerBase<LogEvent, LoggerType, StreamType>;
public:
template<typename... ST>
DebugLogger(ST&... streams) : _ostream(nb::RefPackToPtrVec<std::ostream, ST...>(streams...).vec) {}
~DebugLogger() { static_cast<LoggerType*>(this)->stop(); }
template<typename U>
void log(
U val,
std::string file="",
unsigned int line=0
) { static_cast<LoggerType*>(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
) { static_cast<LoggerType*>(this)->write_message(val, lvl, file, line); }
void error(
const ErrorBase& val,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(val, 0xFF, file, line);
static_cast<LoggerType*>(this)->flush();
}
void error(
const std::string& val,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(Error(val), 0xFF, file, line);
static_cast<LoggerType*>(this)->flush();
}
protected: protected:
std::vector<std::ostream*> _ostream; using LoggerType = LT;
void write_message( 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, std::string msg,
uint8_t lvl=0x00, uint8_t lvl=0x00,
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->push(LogEvent{ type_ptr->in(LogEvent{
std::chrono::system_clock::now(), std::chrono::system_clock::now(),
lvl, lvl,
msg, msg,
@@ -126,7 +109,6 @@ public:
line line
}); });
} }
template <size_t N> template <size_t N>
void write_message( void write_message(
char const(&msg) [N], char const(&msg) [N],
@@ -134,18 +116,16 @@ public:
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->write_message(std::string(msg), lvl, file, line); this->write_message(std::string(msg), lvl, file, line);
} }
void write_message( void write_message(
const ErrorBase& err, const ErrorBase& err,
uint8_t lvl=0x00, uint8_t lvl=0x00,
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->write_message(err.what(), lvl, file, line); this->write_message(err.what(), lvl, file, line);
} }
template<typename U> template<typename U>
std::enable_if_t<std::is_integral_v<U>, void> write_message( std::enable_if_t<std::is_integral_v<U>, void> write_message(
const U& val, const U& val,
@@ -153,38 +133,115 @@ public:
std::string file="", std::string file="",
unsigned int line=0 unsigned int line=0
) { ) {
static_cast<LoggerType*>(this)->write_message(std::to_string(val), lvl, file, line); 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> { class DefaultDebugLogger : public DebugLogger<DefaultDebugLogger> {
protected:
using LoggerType = DefaultDebugLogger; using LoggerType = DefaultDebugLogger;
using Base = DebugLogger<DefaultDebugLogger>; using Base = DebugLogger<DefaultDebugLogger>;
using MultiLogSink = MultiSink<LogEvent>;
template <typename... Ts> using SinkPtr = std::shared_ptr<LogEventHandler>;
struct LogRow; using Base::_logsink;
using Base::write_message;
virtual bool process(const LogEvent& msg) override;
public: public:
using Base::Base; 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(); } ~DefaultDebugLogger() { stop(); }
friend class BufferedDataProcessor<LogEvent, ThreadsafeQueue<LogEvent>, DefaultDebugLogger>; 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);
}; };
extern const bool LOGGER_RUNNING; extern const bool LOGGER_RUNNING;
#ifndef _NB_NO_LOGGER extern const bool LOGGER_RUNNING;
#ifdef _NB_AUTOLOG
extern DefaultDebugLogger logger; extern DefaultDebugLogger logger;
#endif // _NB_NO_LOGGER #endif // _NB_AUTOLOG
// Taking Charge of Adult ADHD by Russell Barkley // Taking Charge of Adult ADHD by Russell Barkley
+52
View File
@@ -0,0 +1,52 @@
#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
+4 -1
View File
@@ -7,7 +7,10 @@
namespace nb { namespace nb {
uint64_t GetPID(); uint64_t GetPID();
uint64_t getTID(); uint64_t GetTID();
extern thread_local const uint64_t CurrentTID;
static const uint64_t MainTID = GetTID();
} // namespace nb } // namespace nb
@@ -2,7 +2,6 @@
#ifndef _NB_STRING_UTILS #ifndef _NB_STRING_UTILS
#define _NB_STRING_UTILS #define _NB_STRING_UTILS
#include <iostream>
#include <string> #include <string>
#include <string_view> #include <string_view>
@@ -21,24 +20,6 @@ namespace nb {
const std::string TABOVER = " "; const std::string TABOVER = " ";
// std::wstring str_to_wstr(std::string in);
// std::string wstr_to_str(std::wstring in);
template <typename Stream, typename... Args>
void stream(const Stream& s, Args&&... args);
template <typename Stream, typename... Args>
void stream(const Stream& s, Args&&... args) {
(s << ... << args);
}
template<typename... Args>
void term(Args&&... args) { stream(std::cout, args..., NEWLINE); }
template<typename... Args>
void wterm(Args&&... args) { stream(std::wcout, args..., nb::WNEWLINE); }
template <typename T = char> template <typename T = char>
std::basic_string<T> find_and_replace( std::basic_string<T> find_and_replace(
ExplicitType_t<std::basic_string<T>> original, ExplicitType_t<std::basic_string<T>> original,
+12 -66
View File
@@ -2,9 +2,8 @@
#ifndef _NB_TYPE_TRAITS #ifndef _NB_TYPE_TRAITS
#define _NB_TYPE_TRAITS #define _NB_TYPE_TRAITS
#include <tuple>
#include <type_traits> #include <type_traits>
#include <vector> #include <utility>
namespace nb { namespace nb {
@@ -31,6 +30,17 @@ namespace detail {
}; };
} // namespace detail } // namespace detail
template<typename K, typename V>
std::pair<K, V> KeyVal(K key, V val) { return std::pair(key, val); }
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{}; struct NoneType{};
template<typename T, unsigned int Arg> template<typename T, unsigned int Arg>
@@ -90,28 +100,6 @@ struct RunAndOutput {
} }
}; };
template<typename Func, std::size_t N=0, typename... Pack>
inline typename std::enable_if<N==sizeof...(Pack), void>::type
ForEach(std::tuple<Pack...>&, Func) {}
template<typename Func, std::size_t N=0, 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... Pack> template<typename T, typename... Pack>
struct Find; struct Find;
@@ -147,48 +135,6 @@ struct Find<T, U> {
>::value; >::value;
}; };
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 } // namespace nb
#endif // _NB_TYPE_TRAITS #endif // _NB_TYPE_TRAITS
+24 -10
View File
@@ -1,14 +1,27 @@
#pragma once #pragma once
#ifndef _NB_CORE_TYPES #ifndef _NB_UTILTIES
#define _NB_CORE_TYPES #define _NB_UTILTIES
#include <mutex> #include <memory>
#include <unordered_map>
#include <vector> #include <vector>
#include <NBCore/Errors.hpp> // #include <NBCore/Errors.hpp>
namespace nb { 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> template<typename T>
using SharedVector = std::vector<std::shared_ptr<T>>; using SharedVector = std::vector<std::shared_ptr<T>>;
@@ -17,7 +30,7 @@ using RValueVector = std::vector<T&&>;
using ByteVector = std::vector<uint8_t>; using ByteVector = std::vector<uint8_t>;
class ObjectManagerError : public Error<ObjectManagerError> { /* class ObjectManagerError : public Error<ObjectManagerError> {
using Base = Error<ObjectManagerError>; using Base = Error<ObjectManagerError>;
public: public:
@@ -29,7 +42,7 @@ class ObjectManagerError : public Error<ObjectManagerError> {
static const std::string type; static const std::string type;
static const ErrorCodeMap ErrorMessages; static const ErrorCodeMap ErrorMessages;
}; }; */
template<typename T> template<typename T>
ByteVector vectorToBytes(const std::vector<T>& vec) { ByteVector vectorToBytes(const std::vector<T>& vec) {
@@ -54,9 +67,10 @@ ByteVector concatVectorBytes(const std::vector<T>& vec1, const std::vector<S>& v
template<typename T> template<typename T>
std::vector<T> bytesToVector(const ByteVector& vec) { std::vector<T> bytesToVector(const ByteVector& vec) {
if (vec.size() % sizeof(T) != 0) { if (vec.size() % sizeof(T) != 0) {
THROW(Error<NoneType>( /* THROW(Error<NoneType>(
std::runtime_error("Data size does not align to std::vector<" + std::string(typeid(T).name()) + ">.") 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); unsigned int num_elmts = vec.size() / sizeof(T);
std::vector<T> ret(num_elmts); std::vector<T> ret(num_elmts);
@@ -65,7 +79,7 @@ std::vector<T> bytesToVector(const ByteVector& vec) {
return ret; return ret;
} }
template <typename T> /* template <typename T>
class ThreadsafeObjectLock; class ThreadsafeObjectLock;
template <typename T> template <typename T>
@@ -114,7 +128,7 @@ class ThreadsafeObjectLock {
_manager->_mutex.lock(); _manager->_mutex.lock();
} }
ThreadsafeObject<T>* const _manager; ThreadsafeObject<T>* const _manager;
}; }; */
} // namespace nb } // namespace nb
#endif // _NB_CORE_TYPES #endif // _NB_CORE_TYPES
+65 -21
View File
@@ -1,38 +1,82 @@
#include <iostream> #include <iostream>
#include <sstream>
#include <NBCore/Logger.hpp> #include <NBCore/Logger.hpp>
#include <NBCore/StringUtils.hpp> #include <NBCore/StringUtils.hpp>
namespace nb { namespace nb {
#ifndef _NB_NO_LOGGER static bool RUN_LOGGER(nb::DefaultDebugLogger& logger_) {
nb::DefaultDebugLogger logger(std::cout); logger_.run();
#endif // _NB_NO_LOGGER return logger_.isRunning();
}
bool nb::DefaultDebugLogger::process(const LogEvent& msg) { #ifdef _NB_AUTOLOG
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 level_field_width = 5;
constexpr size_t msg_prompt_length = level_field_width+7; constexpr size_t msg_prompt_length = level_field_width+7;
for (const auto os : this->_ostream) { std::stringstream formatted_stream;
*os << "["; formatted_stream << "[";
os->width(level_field_width); formatted_stream.width(level_field_width);
*os << std::to_string(msg.lvl) << "] :: "; formatted_stream << std::to_string(msg.lvl) << "] :: ";
std::string fileloc=""; std::string fileloc="";
if (!msg.file.empty()) { if (!msg.file.empty()) {
fileloc += "(" + msg.file + ":" + std::to_string(msg.line) + ") - "; fileloc += "(" + msg.file + ":" + std::to_string(msg.line) + ") - ";
}
*os << indent_strblock(
fileloc + msg.msg,
std::string(20 - msg_prompt_length, ' '),
""
) << nb::NEWLINE;
} }
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; return true;
} }
static bool RUN_LOGGER(nb::DefaultDebugLogger& log) { // class DefaultDebugLogger
return log.run();
bool DefaultDebugLogger::process(const LogEvent& msg) {
return _logsink->in(msg);
} }
const bool LOGGER_RUNNING = RUN_LOGGER(logger);
} // namespace nb } // namespace nb
+2
View File
@@ -26,4 +26,6 @@ uint64_t GetTID() {
#ifdef _NB_TARGET_LINUX #ifdef _NB_TARGET_LINUX
#endif // _NB_TARGET_LINUX #endif // _NB_TARGET_LINUX
thread_local const uint64_t CurrentTID = GetTID();
} // namespace nb } // namespace nb
+17
View File
@@ -0,0 +1,17 @@
#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
+2 -2
View File
@@ -2,7 +2,7 @@
namespace nb { namespace nb {
using ObjectManagerCodes = ObjectManagerError::Codes; /* using ObjectManagerCodes = ObjectManagerError::Codes;
const std::string ObjectManagerError::type = "nb::ObjectManagerError"; const std::string ObjectManagerError::type = "nb::ObjectManagerError";
const ErrorCodeMap ObjectManagerError::ErrorMessages({ const ErrorCodeMap ObjectManagerError::ErrorMessages({
{ObjectManagerCodes::UNDEFINED, "Error"}, {ObjectManagerCodes::UNDEFINED, "Error"},
@@ -22,6 +22,6 @@ const ErrorCodeMap ObjectManagerError::ErrorMessages({
ObjectManagerCodes::BAD_THREAD, ObjectManagerCodes::BAD_THREAD,
"Attempting operation from a bad thread" "Attempting operation from a bad thread"
} }
}); }); */
}; // namespace nb }; // namespace nb
+19 -20
View File
@@ -1,24 +1,23 @@
cmake_minimum_required(VERSION 3.26.0) cmake_minimum_required(VERSION 3.26.0)
if (NB_BUILD_TESTS) enable_testing()
enable_testing() include(GoogleTest)
include(GoogleTest) add_executable(TestCore
add_executable(TestCore ./testErrors.cpp
./testErrors.cpp #./testProcesses.cpp
#./testProcesses.cpp ./testUtils.cpp
./testUtils.cpp )
) target_link_libraries(TestCore
target_link_libraries(TestCore NBCore
NBCore GTest::gtest_main
GTest::gtest_main )
)
add_executable(LoggerTest add_executable(LoggerTest
./testLogger.cpp ./testLogger.cpp
) )
target_link_libraries(LoggerTest target_link_libraries(LoggerTest
NBCore NBCore
) )
gtest_discover_tests(TestCore)
gtest_discover_tests(TestCore)
endif()
+6 -3
View File
@@ -1,3 +1,4 @@
#define _NB_AUTOLOG
#include <exception> #include <exception>
#include <NBCore/Errors.hpp> #include <NBCore/Errors.hpp>
@@ -29,17 +30,19 @@ const nb::ErrorCodeMap TestError::ErrorMessages{
}; };
int main() { int main() {
nb::logger.log("Whoop!"); while(!nb::LOGGER_RUNNING) {}
nb::logger.minimalLogLevel(0x0);
nb::logger.msg("Whoop!");
try { try {
THROW(TestError(0, TestError(1, TestError(2, TestError(3, TestError(2)))))); THROW(TestError(0, TestError(1, TestError(2, TestError(3, TestError(2))))));
} catch (TestError e){ } catch (TestError e){
nb::logger.log("nb::Error was thrown!"); nb::logger.msg("nb::Error was thrown!");
} }
try { try {
THROW(std::exception()); THROW(std::exception());
} catch (std::exception e){ } catch (std::exception e){
nb::logger.log("std::exception was thrown!"); nb::logger.msg("std::exception was thrown!");
} }
ERROR("hello there!"); ERROR("hello there!");
return 0; return 0;
+20 -40
View File
@@ -3,6 +3,7 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <string> #include <string>
#include <NBCore/DataTypes.hpp>
#include <NBCore/TypeTraits.hpp> #include <NBCore/TypeTraits.hpp>
#include <NBCore/StringUtils.hpp> #include <NBCore/StringUtils.hpp>
@@ -22,7 +23,7 @@ TEST(UtilsTest, TestFindAndReplace) {
tmp = find_and_replace("aeiou", "a", "afa"); tmp = find_and_replace("aeiou", "a", "afa");
tmp = find_and_replace(tmp, "e", "efe"); tmp = find_and_replace(tmp, "e", "efe");
tmp = find_and_replace(tmp, "i", "ifi"); tmp = find_and_replace(tmp, "i", "ifi");
tmp = find_and_replace(tmp, "o", "ofo"); tmp = find_and_replace(tmp, "o", "ofo");
tmp = find_and_replace(tmp, "u", "ufu"); tmp = find_and_replace(tmp, "u", "ufu");
ASSERT_STREQ( ASSERT_STREQ(
@@ -46,7 +47,6 @@ TEST(UtilsTest, TestFindAndReplaceWstr) {
find_and_replace<wchar_t>(L"Jeff", L"e", L"efe").c_str(), find_and_replace<wchar_t>(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<wchar_t>(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<wchar_t>(tmp, L"i", L"ifi").c_str(),
@@ -74,44 +74,6 @@ TEST(UtilsTest, TestFindAndReplaceWstr) {
); );
} }
/* TEST(UtilsTest, TestWstrToStr) {
ASSERT_STREQ(
nb::wstr_to_str(L"Hi!").c_str(),
"Hi!"
);
ASSERT_STREQ(
nb::wstr_to_str(L"Naif").c_str(),
"Naif"
);
ASSERT_STREQ(
nb::wstr_to_str(L"\r\r\r\n").c_str(),
"\r\r\r\n"
);
ASSERT_STREQ(
nb::wstr_to_str(L"Naif\ttalks\r\ra\t\nlot").c_str(),
"Naif\ttalks\r\ra\t\nlot"
);
} */
/* TEST(UtilsTest, TestStrToWstr) {
ASSERT_STREQ(
nb::str_to_wstr("Hi!").c_str(),
L"Hi!"
);
ASSERT_STREQ(
nb::str_to_wstr("Naif").c_str(),
L"Naif"
);
ASSERT_STREQ(
nb::str_to_wstr("\r\r\r\n").c_str(),
L"\r\r\r\n"
);
ASSERT_STREQ(
nb::str_to_wstr("Naif\ttalks\r\ra\t\nlot").c_str(),
L"Naif\ttalks\r\ra\t\nlot"
);
} */
struct A { bool x(); }; struct A { bool x(); };
struct B { bool y(); }; struct B { bool y(); };
struct C { bool x(); bool y; }; struct C { bool x(); bool y; };
@@ -145,4 +107,22 @@ TEST(UtilsTest, TestIsDetected) {
ASSERT_TRUE(ret); ASSERT_TRUE(ret);
} }
TEST(DataTypesTests, TestNDArray) {
float* data_f = new float[9] {0,1,2,3,4,5,6,7,8};
nb::NDArray<float, 2> arr({3, 3}, data_f);
ASSERT_FLOAT_EQ(data_f[4], arr.at({1,1}));
arr.at({1,1}) = 0.5;
ASSERT_FLOAT_EQ(0.5, arr.at({1,1}));
delete[] data_f;
unsigned int* data_ui = new unsigned int[8] {0,1,2,3,4,5,6,7};
nb::NDArray<unsigned int, 3> arr3d({2,2,2}, data_ui);
ASSERT_EQ(data_ui[5], arr3d.at({1,0,1}));
arr3d.at({0,1,1}) = 23;
ASSERT_EQ(23, arr3d.at({0,1,1}));
delete[] data_ui;
}
} // namespace nb } // namespace nb
+70
View File
@@ -0,0 +1,70 @@
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()
+2
View File
@@ -0,0 +1,2 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/NBDataTargets.cmake")
+252
View File
@@ -0,0 +1,252 @@
#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
+6
View File
@@ -0,0 +1,6 @@
#include <NBCore/Errors.hpp>
#include <NBData/FFT.hpp>
namespace nb {
} // namespace nb
+22
View File
@@ -0,0 +1,22 @@
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()
+5
View File
@@ -0,0 +1,5 @@
#include <NBData/FFT.hpp>
int main() {
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
#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);
}
+68
View File
@@ -0,0 +1,68 @@
#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
);
}
}
+37 -23
View File
@@ -1,10 +1,11 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(NBGraphics VERSION 0.1) project(NBGraphics VERSION 0.1)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
set(GLAD_PATH ${NBENGINE_ROOT}/../glad/) set(GLAD_PATH ${NBENGINE_ROOT}/../glad/)
set(STBIMAGE_PATH ${NBENGINE_ROOT}/../stbi_image)
get_filename_component(GLAD_PATH ${GLAD_PATH} ABSOLUTE) get_filename_component(GLAD_PATH ${GLAD_PATH} ABSOLUTE)
get_filename_component(STBIMAGE_PATH ${STBIMAGE_PATH} ABSOLUTE)
set(CMAKE_PREFIX_PATH set(CMAKE_PREFIX_PATH
"${CMAKE_PREFIX_PATH}" "${CMAKE_PREFIX_PATH}"
@@ -21,27 +22,34 @@ else()
endif() 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/Buffers.cpp
./src/FrameBuffers.cpp ./src/FrameBuffers.cpp
./src/Image.cpp ./src/Image.cpp
./src/Mesh.cpp
./src/OGLObjects.cpp ./src/OGLObjects.cpp
./src/ProgramPipeline.cpp ./src/ProgramPipeline.cpp
./src/Textures.cpp ./src/Textures.cpp
./src/VertexArray.cpp ./src/VertexArray.cpp
./src/VertexData.cpp
./src/Window.cpp ./src/Window.cpp
) )
toAbsolutePath(NB_GRAPHICS_INCLUDE toAbsolutePath(NB_GRAPHICS_INCLUDE
./include/NBGraphics/Buffers.hpp ./include/NBGraphics/Buffers.hpp
./include/NBGraphics/Camera.hpp ./include/NBGraphics/Camera.hpp
./include/NBGraphics/Draw.hpp
./include/NBGraphics/FrameBuffers.hpp ./include/NBGraphics/FrameBuffers.hpp
./include/NBGraphics/GLLoad.hpp ./include/NBGraphics/GLLoad.hpp
./include/NBGraphics/Image.hpp ./include/NBGraphics/Image.hpp
./include/NBGraphics/Mesh.hpp
./include/NBGraphics/OGLObjects.hpp ./include/NBGraphics/OGLObjects.hpp
./include/NBGraphics/ProgramPipeline.hpp ./include/NBGraphics/ProgramPipeline.hpp
./include/NBGraphics/Textures.hpp ./include/NBGraphics/Textures.hpp
./include/NBGraphics/VertexArray.hpp ./include/NBGraphics/VertexArray.hpp
./include/NBGraphics/VertexData.hpp
./include/NBGraphics/Window.hpp ./include/NBGraphics/Window.hpp
) )
@@ -53,29 +61,45 @@ add_library(NBGraphics
${GLAD_PATH}/src/glad.c ${GLAD_PATH}/src/glad.c
) )
add_library(NBEngine::Graphics ALIAS NBGraphics) add_library(NBEngine::Graphics ALIAS NBGraphics)
add_dependencies(NBGraphics NBCore)
add_dependencies(NBGraphics glfw)
target_link_libraries(NBGraphics target_link_libraries(NBGraphics
PUBLIC glfw PUBLIC glfw
PUBLIC NBCore PUBLIC NBCore
) )
get_target_property(GLFW_INTERFACE_INCLUDES glfw INTERFACE_INCLUDE_DIRECTORIES)
#include_directories(${GLFW_INTERFACE_INCLUDES})
target_include_directories(NBGraphics target_include_directories(NBGraphics
PUBLIC "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>" PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" PUBLIC "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>"
PUBLIC "${STBIMAGE_PATH}"
PUBLIC "${GLAD_PATH}/include" 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) if (NBENGINE_INSTALL)
message("Installing NBGraphics to ${CMAKE_INSTALL_PREFIX}") message("Installing NBGraphics to ${CMAKE_INSTALL_PREFIX}")
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
install( install(
TARGETS NBGraphics TARGETS NBGraphics
EXPORT NBGraphicsTargets EXPORT NBGraphicsTargets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
INCLUDES DESTINATION include
) )
install( install(
DIRECTORY "${PROJECT_SOURCE_DIR}/include/NBGraphics" DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/NBGraphics"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp" FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
) )
@@ -84,20 +108,10 @@ if (NBENGINE_INSTALL)
DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
NAMESPACE NBEngine:: NAMESPACE NBEngine::
) )
configure_package_config_file(
"NBGraphicsConfig.cmake.in"
"NBGraphicsConfig.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX}/cmake
PATH_VARS CMAKE_INSTALL_LIBDIR
)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/NBGraphicsConfigVersion.cmake"
COMPATIBILITY AnyNewerVersion
)
install(FILES install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/NBGraphicsConfig.cmake" "${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfig.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/NBGraphicsConfigVersion.cmake" "${CMAKE_BINARY_DIR}/cmake/NBGraphicsConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_PREFIX}/cmake" DESTINATION "${CMAKE_INSTALL_PREFIX}/CMake"
) )
endif() endif()
@@ -1,2 +1,6 @@
@PACKAGE_INIT@ @PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/NBGraphicsTargets.cmake") include("${CMAKE_CURRENT_LIST_DIR}/NBGraphicsTargets.cmake")
include(CMakeFindDependencyMacro)
find_dependency(NBCore REQUIRED)
find_dependency(OpenGL REQUIRED)
find_dependency(glfw3 REQUIRED)
+106 -61
View File
@@ -14,7 +14,7 @@
namespace nb { namespace nb {
extern const std::unordered_map<GLenum, std::string> BufferTypes; extern const ConstantMap <GLenum, std::string> BufferTypes;
template<GLenum N> template<GLenum N>
struct GLSLEnum; struct GLSLEnum;
@@ -57,7 +57,8 @@ class BufferError : public Error<BufferError> {
enum Codes : unsigned int { enum Codes : unsigned int {
UNDEFINED, UNDEFINED,
DATA_OVERFLOW, DATA_OVERFLOW,
DATA_ERROR DATA_ERROR,
BAD_DATA_TYPE
}; };
static const std::string type; static const std::string type;
static const ErrorCodeMap ErrorMessages; static const ErrorCodeMap ErrorMessages;
@@ -69,18 +70,17 @@ class Buffer : public OpenGLObject {
using OpenGLObject::_id; using OpenGLObject::_id;
GLenum _usage = GL_STATIC_DRAW; GLenum _usage = GL_STATIC_DRAW;
size_t _size; size_t _size;
Buffer(GLenum target) : Target(target) {}
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
glGenBuffers(1, &_id); OPENGL_CALL(glGenBuffers(1, &_id));
} }
bind(); this->bind();
return _id; return _id;
} }
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
unbind(); this->unbind();
glDeleteBuffers(1, &_id); OPENGL_CALL(glDeleteBuffers(1, &_id));
_id = 0; _id = 0;
} }
} }
@@ -88,20 +88,24 @@ class Buffer : public OpenGLObject {
public: public:
const GLenum Target; const GLenum Target;
using OpenGLObject::OpenGLObject; using OpenGLObject::OpenGLObject;
Buffer(GLenum target);
Buffer(GLenum target, const ByteVector&, GLenum usage=GL_STATIC_DRAW);
Buffer(Buffer&& other); Buffer(Buffer&& other);
Buffer& operator=(Buffer&& rhs); Buffer& operator=(Buffer&& rhs);
virtual void bind() const override { virtual void bind() const override {
if (_id) { if (_id) {
glBindBuffer(Target, _id); OPENGL_CALL(glBindBuffer(Target, _id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ BufferType " + BufferTypes.at(Target) "w/ BufferType " + BufferTypes[Target]
)); ));
} }
} }
virtual void unbind() const override { glBindBuffer(Target, 0); } virtual void unbind() const override {
OPENGL_CALL(glBindBuffer(Target, 0));
}
GLenum usage() const; GLenum usage() const;
size_t size() const; size_t size() const;
ByteVector data() const; ByteVector data() const;
@@ -149,67 +153,108 @@ protected:
}; */ }; */
class ArrayBuffer : public Buffer { class UniformBuffer : public Buffer {
protected:
GLuint _index;
public: public:
template<typename T> UniformBuffer();
ArrayBuffer(const std::vector<T>& data, GLenum usage=GL_STATIC_DRAW) void bind() const override;
: Buffer(GL_ARRAY_BUFFER) { GLuint bufferIndex() const;
Buffer::data(vectorToBytes(data), usage); GLuint bufferIndex(GLuint);
}
}; };
class ElementBuffer : protected Buffer { 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: protected:
GLenum _glslType; using Codes = BufferError::Codes;
size_t _typeSize; 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: public:
using Buffer::Target; using Buffer::Target;
using Buffer::OpenGLObject;
using Buffer::bind; using Buffer::bind;
using Buffer::usage;
using Buffer::unbind; using Buffer::unbind;
ElementBuffer(); using Buffer::usage;
using Buffer::size;
template<typename T> template<typename T>
ElementBuffer(const T* const data_ptr, size_t size, GLenum usage=GL_STATIC_DRAW) ElementBuffer(const std::vector<T>& indices, GLenum usage=GL_STATIC_DRAW) : Buffer(GL_ELEMENT_ARRAY_BUFFER) {
: Buffer(GL_ELEMENT_ARRAY_BUFFER) { data(indices, usage);
data(data_ptr, size, usage);
}
template<typename T>
ElementBuffer(const std::vector<T>& data_, GLenum usage_=GL_STATIC_DRAW)
: ElementBuffer(data_.data(), data_.size(), usage_) {}
size_t size() const;
size_t typeSize() const;
ByteVector data() const;
GLenum glslType() const;
template<typename T>
void data(const T* data_, size_t size_, GLenum usage_=GL_STATIC_DRAW) {
declare();
using TypeInfo = GLSLType<T>;
_typeSize = TypeInfo::size;
Buffer::data(data_, size_*_typeSize, usage_);
_glslType = TypeInfo::value;
}
template<typename T>
void data(const std::vector<T>& data_, GLenum usage_=GL_STATIC_DRAW) {
data(data_.data(), data_.size(), usage_);
}
template<typename T>
void subdata(const T* data, size_t size, size_t offset) {
using TypeInfo = GLSLType<T>;
if ( _glslType != TypeInfo::value ) {
THROW( BufferError(
Codes::DATA_ERROR,
"Check element buffer data types"
) );
}
Buffer::subdata(data, size*_typeSize, offset);
}
template<typename T>
void subdata(const std::vector<T>& data, size_t offset=0) {
subdata(data.data(), data.size(), offset);
} }
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);
}
}; };
@@ -1,84 +0,0 @@
#pragma once
#ifndef _NB_DRAW
#define _NB_DRAW
#include <NBGraphics/GLLoad.hpp>
#include <exception>
#include <map>
#include <string>
#include <vector>
#include <NBGraphics/Buffers.h>
#include <NBGraphics/Shader.h>
#include <NBGraphics/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
@@ -29,19 +29,25 @@ class RenderBuffer : public RenderTarget {
protected: protected:
GLuint declare() override { GLuint declare() override {
if (!_id) { if (!_id) {
glRenderbufferStorage( OPENGL_CALL(
glGenRenderbuffers(1, &_id)
);
bind();
OPENGL_CALL(glRenderbufferStorage(
GL_RENDERBUFFER, GL_RENDERBUFFER,
format, format,
width, width,
height height
); ));
return _id;
} }
bind();
return _id; return _id;
} }
void remove() override { void remove() override {
if (_id) { if (_id) {
unbind(); unbind();
glDeleteRenderbuffers(1, &_id); OPENGL_CALL(glDeleteRenderbuffers(1, &_id));
_id = 0; _id = 0;
} }
} }
@@ -50,11 +56,14 @@ class RenderBuffer : public RenderTarget {
const unsigned int width; const unsigned int width;
const unsigned int height; const unsigned int height;
const GLenum format; const GLenum format;
template<typename PixelType> RenderBuffer(
RenderBuffer(unsigned int width_, unsigned int height_) : GLenum format_,
unsigned int width_,
unsigned int height_
) :
format(format_),
width(width_), width(width_),
height(height_), height(height_),
format(OGLPixelFormat<PixelType>::glFormat),
RenderTarget(GL_RENDERBUFFER) RenderTarget(GL_RENDERBUFFER)
{ declare(); } { declare(); }
RenderBuffer(RenderBuffer&& rhs) : RenderBuffer(RenderBuffer&& rhs) :
@@ -66,16 +75,16 @@ class RenderBuffer : public RenderTarget {
RenderBuffer& operator=(RenderBuffer&&) = delete; RenderBuffer& operator=(RenderBuffer&&) = delete;
void bind() const override { void bind() const override {
if (_id) { if (_id) {
glBindRenderbuffer(GL_RENDERBUFFER, _id); OPENGL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, _id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ RenderBuffer" "w/ RenderBuffer"
)); ));
} }
} }
void unbind() const override { void unbind() const override {
glBindRenderbuffer(GL_RENDERBUFFER, 0); OPENGL_CALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));
} }
}; };
@@ -85,8 +94,10 @@ class FrameBufferBase : public OpenGLObject {
static bool texTypeIs2D(GLenum texType) { static bool texTypeIs2D(GLenum texType) {
switch(texType) { switch(texType) {
case GL_TEXTURE_2D: case GL_TEXTURE_2D:
default:
return true; return true;
case GL_TEXTURE_1D:
default:
return false;
break; break;
} }
} }
@@ -98,6 +109,19 @@ class FrameBufferBase : public OpenGLObject {
GLuint declare() override; GLuint declare() override;
void remove() override; void remove() override;
std::shared_ptr<RenderTarget> detach(GLenum); 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( void attach(
GLenum attachment, GLenum attachment,
std::shared_ptr<Texture> texture, std::shared_ptr<Texture> texture,
@@ -109,32 +133,6 @@ class FrameBufferBase : public OpenGLObject {
unsigned int level, unsigned int level,
unsigned int layer unsigned int layer
); );
void attach(
GLenum attachment,
std::shared_ptr<RenderBuffer> renderBuffer
) {
declare();
if (attachment == GL_NONE) {
THROW(FrameBufferError(FrameBufferError::INVALID_VALUE,
"Cannot attach RenderBuffer to `GL_NONE`"
));
}
glFramebufferRenderbuffer(
Target,
attachment,
GL_RENDERBUFFER,
renderBuffer->id()
);
_attachments[attachment] = renderBuffer;
}
public:
const GLenum Target;
void bind() const override;
void unbind() const override;
GLenum status() const;
AttachmentMap getAllBuffers() const;
std::shared_ptr<RenderTarget> getBuffer(GLenum) const;
}; };
class ReadFrameBuffer; class ReadFrameBuffer;
@@ -178,12 +176,6 @@ class WriteFrameBuffer : public virtual FrameBufferBase {
WriteFrameBuffer(); WriteFrameBuffer();
WriteFrameBuffer& operator=(ReadFrameBuffer&&); WriteFrameBuffer& operator=(ReadFrameBuffer&&);
WriteFrameBuffer& operator=(WriteFrameBuffer&&); WriteFrameBuffer& operator=(WriteFrameBuffer&&);
template<typename... T>
void attach(
GLenum attachment,
std::shared_ptr<Texture> texture,
T... args
) { FrameBufferBase::attach(attachment, texture, args...); }
DrawTexVec getWriteBuffers() const; DrawTexVec getWriteBuffers() const;
std::vector<GLenum> getWriteLocations() const; std::vector<GLenum> getWriteLocations() const;
DrawTexVec setWriteBuffers(const std::vector<GLenum>& attachments); DrawTexVec setWriteBuffers(const std::vector<GLenum>& attachments);
@@ -5,4 +5,8 @@
#include <glad/glad.h> #include <glad/glad.h>
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
namespace nb {
} // namespace nb
#endif #endif
+82 -41
View File
@@ -134,40 +134,104 @@ class Image;
template<typename T, typename... Channels> template<typename T, typename... Channels>
class Image<Pixel<T, 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: protected:
using Codes = ImageError::Codes; using Codes = ImageError::Codes;
bool _data_managed;
T* _data; T* _data;
Image(unsigned int x, unsigned int y) Image(unsigned int x, unsigned int y, T* data, bool managed)
: width(x), height(y), _data(nullptr) {} : width(x), height(y), _data(data), _data_managed(managed) {}
void clear() {
if (_data_managed) {
delete[] _data;
_data_managed = false;
}
_data = nullptr;
}
public: public:
using PixelType = Pixel<T, Channels...>; using PixelType = Pixel<T, Channels...>;
static constexpr size_t NumberChannels = sizeof...(Channels); static constexpr size_t NumberChannels = sizeof...(Channels);
const unsigned int width; const unsigned int width;
const unsigned int height; const unsigned int height;
Image(unsigned int x, unsigned int y, const T* data) static Image CreateImageStorage(
: Image(x, y) { unsigned int width,
size_t data_size = width*height*NumberChannels; unsigned int height,
_data = new T[data_size]; T* data=nullptr
std::memcpy(_data, data, data_size*sizeof(T)); ) {
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(const Image&) = delete;
Image& operator=(const Image&) = delete;
Image& operator=(Image&&) = delete;
Image(Image&& mv) Image(Image&& mv)
: width(mv.width), height(mv.height), _data(mv._data) { : Image(mv.width, mv.height) {
mv._data = nullptr; *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;
} }
~Image() { virtual ~Image() {
if (_data) { clear();
delete[] _data;
}
} }
const T* data() const { return _data; } const T* data() const { return _data; }
Image&& copy() const { Image<PixelType> copy() const {
return Image(width, height, _data); return CreateImageStorage(width, height, _data);
} }
PixelReference<PixelType> at(unsigned int x, unsigned int y) { PixelReference<PixelType> at(unsigned int x, unsigned int y) {
if (!(x<width) || !(y<height)) { if (!(x<width) || !(y<height)) {
@@ -188,29 +252,6 @@ class Image<Pixel<T, Channels...>> {
}; };
template<typename... T>
class ImageReference;
template<typename T, typename... Channels>
class ImageReference<Pixel<T, Channels...>> : public Image<Pixel<T, Channels...>> {
protected:
using Base = Image<Pixel<T, Channels...>>;
using Base::_data;
public:
using Base::width;
using Base::height;
using Base::copy;
ImageReference(unsigned int x, unsigned int y, T* data)
: Base(x, y) {
_data = data;
}
~ImageReference() noexcept {
Base::_data = nullptr;
}
};
} // namespace nb } // namespace nb
#endif // _NB_IMAGE #endif // _NB_IMAGE
@@ -0,0 +1,81 @@
#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
@@ -2,20 +2,48 @@
#ifndef _NB_OGL_OBJECTS #ifndef _NB_OGL_OBJECTS
#define _NB_OGL_OBJECTS #define _NB_OGL_OBJECTS
#include <NBGraphics/GLLoad.hpp>
#include <NBCore/Errors.hpp> #include <NBCore/Errors.hpp>
#include <NBGraphics/GLLoad.hpp>
#include <NBCore/Utils.hpp>
namespace nb { namespace nb {
class OGLError : public Error<OGLError> { typedef ConstantMap<GLenum, std::string> GLEnumTableType;
using Base = Error<OGLError>;
extern const GLEnumTableType GLenumTable;
extern const ConstantMap<TypeCodes, GLint> TypeToGLSL;
class OpenGLError : public Error<OpenGLError> {
using Base = Error<OpenGLError>;
public: public:
using Base::Base; using Base::Base;
enum Codes : unsigned int { enum Codes : unsigned int {
UNDEFINED, HANGING_OBJECT, INVALID_OBJECT 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 std::string type;
@@ -34,15 +62,57 @@ class OpenGLObject {
virtual void unbind() const = 0; virtual void unbind() const = 0;
GLuint id() const { return _id; } GLuint id() const { return _id; }
protected:
using Codes = OGLError::Codes;
OpenGLObject() = default;
protected:
using Codes = OpenGLObjectError::Codes;
OpenGLObject();
void checkObjectContextValidity();
virtual GLuint declare() = 0; virtual GLuint declare() = 0;
virtual void remove() = 0; virtual void remove() = 0;
const GLFWwindow* const _arena;
GLuint _id = 0; GLuint _id = 0;
}; };
} // namespace nb } // 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 #endif // _NB_OGL_OBJECTS
@@ -9,6 +9,7 @@
#include <NBCore/Errors.hpp> #include <NBCore/Errors.hpp>
#include <NBCore/Utils.hpp> #include <NBCore/Utils.hpp>
#include <NBGraphics/Buffers.hpp>
#include <NBGraphics/OGLObjects.hpp> #include <NBGraphics/OGLObjects.hpp>
namespace nb { namespace nb {
@@ -78,8 +79,8 @@ class Shader : public OpenGLObject {
for (int i=0; i < num_srcs; ++i) { for (int i=0; i < num_srcs; ++i) {
src_ptrs[i] = _sources[i].data(); src_ptrs[i] = _sources[i].data();
} }
glShaderSource(_id, num_srcs, src_ptrs.data(), NULL); OPENGL_CALL(glShaderSource(_id, num_srcs, src_ptrs.data(), NULL));
glCompileShader(_id); OPENGL_CALL(glCompileShader(_id));
_success = status(GL_COMPILE_STATUS); _success = status(GL_COMPILE_STATUS);
if (!_success) { if (!_success) {
WARN(log(), 0x0FE); WARN(log(), 0x0FE);
@@ -88,14 +89,14 @@ class Shader : public OpenGLObject {
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
_id = _id = glCreateShader(target); _id = _id = OPENGL_CALL(glCreateShader(target));
} }
return _id; return _id;
} }
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
glDeleteShader(_id); OPENGL_CALL(glDeleteShader(_id));
} }
} }
@@ -112,26 +113,31 @@ class Program : public OpenGLObject {
Program& operator=(Program&&) = delete; Program& operator=(Program&&) = delete;
operator bool(); operator bool();
~Program() { remove(); } ~Program() { remove(); }
virtual void bind() const override { void bind() const override {
glUseProgram(_id); OPENGL_CALL(glUseProgram(_id));
} }
virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ } void unbind() const override { /* TODO: Some warning of some kind perhaps*/ }
GLint status(GLenum) const; GLint status(GLenum) const;
std::string log() 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; friend Base;
protected: protected:
using Base::_id; using Base::_id;
GLint _success; GLint _success;
std::unordered_map<std::string, GLuint> _uniformBindings;
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
_id = glCreateProgram(); _id = OPENGL_CALL(glCreateProgram());
} }
return _id; return _id;
} }
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
glDeleteProgram(_id); OPENGL_CALL(glDeleteProgram(_id));
} }
} }
+152 -38
View File
@@ -6,6 +6,8 @@
#include <NBGraphics/Image.hpp> #include <NBGraphics/Image.hpp>
#include <NBGraphics/OGLObjects.hpp> #include <NBGraphics/OGLObjects.hpp>
/*! @file Textures.hpp */
namespace nb { namespace nb {
class TextureBuffer : public virtual Buffer { class TextureBuffer : public virtual Buffer {
@@ -14,20 +16,25 @@ class TextureBuffer : public virtual Buffer {
}; };
/*!
@brief An OpenGL object that may be rendered to within a Framebuffer.
*/
class RenderTarget : public OpenGLObject { class RenderTarget : public OpenGLObject {
protected: protected:
using Base = OpenGLObject; using Base = OpenGLObject;
using Base::_id; using Base::_id;
RenderTarget(GLenum target) : Target(target) {} RenderTarget(GLenum target) : Target(target) {}
RenderTarget(RenderTarget&& rhs)
: Target(rhs.Target), Base(std::move(rhs)) {}
public: public:
using Base::Base;
using Base::id; using Base::id;
RenderTarget(RenderTarget&& mv);
RenderTarget& operator=(RenderTarget&& mv);
const GLenum Target; const GLenum Target;
}; };
/*!
@brief An OpenGL Target object
*/
class Texture : public RenderTarget { class Texture : public RenderTarget {
protected: protected:
using Base = RenderTarget; using Base = RenderTarget;
@@ -35,7 +42,7 @@ class Texture : public RenderTarget {
Texture(GLenum); Texture(GLenum);
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
glGenTextures(1, &_id); OPENGL_CALL(glGenTextures(1, &_id));
} }
bind(); bind();
return _id; return _id;
@@ -43,57 +50,71 @@ class Texture : public RenderTarget {
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
bind(); bind();
glDeleteTextures(0, &_id); OPENGL_CALL(glDeleteTextures(0, &_id));
} }
} }
public: public:
using Base::Base;
using Base::id; using Base::id;
using Base::Target; using Base::Target;
Texture(Texture&& mv);
Texture& operator=(Texture&& mv);
virtual void bind() const override { void bind() const override {
if (_id) { if (_id) {
glBindTexture(Target, _id); OPENGL_CALL(glBindTexture(Target, _id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ Texture" "w/ Texture"
)); ));
} }
} }
virtual void unbind() const override { void unbind() const override {
glBindTexture(Target, 0); OPENGL_CALL(glBindTexture(Target, 0));
} }
template <typename T> template <typename T>
void parameter(GLenum param_, const T& val_); 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_) { void parameter(GLenum param_, const int& val_) {
declare(); declare();
glTexParameteri(_id, param_, val_); OPENGL_CALL(
} glTexParameteri(Target, param_, val_)
void parameter(GLenum param_, const std::vector<int>& val_) { );
declare();
glTexParameteriv(_id, param_, val_.data());
} }
void parameter(GLenum param_, const std::vector<float>& val_) { void parameter(GLenum param_, const std::vector<float>& val_) {
declare(); declare();
glTexParameterfv(_id, param_, val_.data()); 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_) { void parameter(GLenum param_, const std::vector<unsigned int>& val_) {
declare(); declare();
glTexParameterIuiv(_id, param_, val_.data()); OPENGL_CALL(
glTexParameterIuiv(Target, param_, val_.data())
);
} }
void generateMipmaps() const { void generateMipmaps() const {
bind(); bind();
glGenerateMipmap(Target); OPENGL_CALL(
glGenerateMipmap(Target)
);
} }
}; };
template<typename T>
class ImageTexture;
template<typename T> template<typename T>
struct OGLPixelFormat; struct OGLPixelFormat;
@@ -101,53 +122,146 @@ template<typename T, typename... Channels>
struct OGLPixelFormat<Pixel<T, Channels...>>; struct OGLPixelFormat<Pixel<T, Channels...>>;
template<> template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue>> { struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> {
static constexpr GLenum glFormat = GL_RGB; static constexpr GLenum glBase = GL_RGBA;
static constexpr GLenum glFormat = GL_RGBA8UI;
static constexpr GLenum glData = GL_UNSIGNED_BYTE; static constexpr GLenum glData = GL_UNSIGNED_BYTE;
}; };
template<> template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> { struct OGLPixelFormat<Pixel<float, Red, Green, Blue, Alpha>> {
static constexpr GLenum glFormat = GL_RGBA; 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; 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> template<typename T, typename... Channels>
class ImageTexture<Pixel<T, Channels...>> : public Texture { class Texture2D<Pixel<T, Channels...>> : public Texture {
protected: protected:
using Texture::Texture; using Texture::Texture;
using PixelType = Pixel<T, Channels...>; using PixelType = Pixel<T, Channels...>;
public: public:
using Texture::generateMipmaps; using Texture::generateMipmaps;
ImageTexture() : Texture(GL_TEXTURE_2D) {} Texture2D() : Texture(GL_TEXTURE_2D) {}
ImageTexture(ImageTexture&& cpy) { Texture2D(Texture2D&& cpy) {
*this = std::move(cpy); *this = std::move(cpy);
} }
ImageTexture& operator=(ImageTexture&& rhs) { Texture2D& operator=(Texture2D&& rhs) {
return Texture::operator=(std::move(rhs)); return Texture::operator=(std::move(rhs));
} }
void setImage(const Image<PixelType>& img, unsigned int layer) { void setLayer(const Image<PixelType>& img, unsigned int layer) {
using Format = OGLPixelFormat<PixelType>; using Format = OGLPixelFormat<PixelType>;
declare(); declare();
glTexImage2D( auto data = img.data();
OPENGL_CALL(glTexImage2D(
Target, Target,
layer, layer,
Format::glFormat, Format::glFormat,
img.width, img.width,
img.height, img.height,
0, 0,
Format::glFormat, Format::glBase,
Format::glData, Format::glData,
img.data() data ? data : nullptr
); ));
} }
void setImage(const Image<PixelType>& img, bool generateMipmap=true) { void setTexture(const Image<PixelType>& img, bool generateMipmap=true) {
setImage(img, (unsigned int)0); setLayer(img, 0);
if (generateMipmap) { generateMipmaps(); } 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 } // namespace nb
#endif // _NB_TEXTURES #endif // _NB_TEXTURES
@@ -8,6 +8,7 @@
#include <NBGraphics/Buffers.hpp> #include <NBGraphics/Buffers.hpp>
#include <NBGraphics/OGLObjects.hpp> #include <NBGraphics/OGLObjects.hpp>
#include <NBGraphics/VertexData.hpp>
namespace nb { namespace nb {
@@ -33,32 +34,13 @@ static uint8_t GLSLTypeSize(GLenum type) {
} }
} }
struct VertexAttributeLayout {
int32_t offset = 0;
GLsizei stride = 0;
GLuint divisor = 0;
};
struct VertexAttribute {
GLint GLSLSize;
GLenum GLSLType;
GLboolean GLSLNormalization;
VertexAttributeLayout layout;
};
struct VertexAttributePointer {
VertexAttribute attribute;
GLuint buffer;
GLuint index;
};
static bool isIndexInVertexAttribute(int i, const VertexAttribute& va) { static bool isIndexInVertexAttribute(int i, const VertexAttribute& va) {
if ((i -= va.layout.offset) < 0) { return false; } if ((i -= va.layout.offset) < 0) { return false; }
return (i%va.layout.stride) < GLSLTypeSize(va.GLSLType) * va.GLSLSize; return (i%va.layout.stride) < GLSLTypeSize(TypeToGLSL[va.type]) * va.size;
} }
typedef std::vector<VertexAttribute> VertexAttributeList; typedef std::vector<VertexData> VertexDataList;
typedef std::vector<VertexAttributePointer> VertexAttributePointerList; typedef std::vector<VertexDataPointer> VertexDataPointerList;
class VAOError : public Error<VAOError> { class VAOError : public Error<VAOError> {
using Base = Error<VAOError>; using Base = Error<VAOError>;
@@ -78,54 +60,57 @@ class VAO : public OpenGLObject {
using Base = OpenGLObject; using Base = OpenGLObject;
using Codes = VAOError::Codes; 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: public:
using Base::Base; using Base::Base;
VAO() = default; VAO() = default;
VAO(const VertexAttributePointerList&); VAO(const VertexDataPointerList&);
VAO(VAO&&); VAO(VAO&&);
VAO& operator=(VAO&&); VAO& operator=(VAO&&);
virtual void bind() const override { virtual void bind() const override {
if(_id) { if(_id) {
glBindVertexArray(_id); OPENGL_CALL(glBindVertexArray(_id));
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ VertexArrayObject" "w/ VertexArrayObject"
)); ));
} }
} }
virtual void unbind() const override { glBindVertexArray(0); } virtual void unbind() const override {
OPENGL_CALL(glBindVertexArray(0));
}
VertexAttributePointerList attributes() const; VertexDataPointerList attributes() const;
VertexAttributePointerList attributes(const VertexAttributePointerList&); VertexDataPointerList attributes(const VertexDataPointerList&);
VertexAttributePointer attr(GLuint) const; VertexDataPointerList attributes(const VertexDataList&);
VertexDataPointer attribute(GLuint) const;
void enable() const; void enable() const;
void enable(GLuint) const; void enable(GLuint) const;
void disable() const; void disable() const;
void disable(GLuint) const; void disable(GLuint) const;
protected:
using Base::_id;
VertexAttributePointerList _attrs;
virtual void remove() override {
if(_id) {
disable();
bind();
glDeleteVertexArrays(1, &_id);
_id = 0;
}
}
virtual GLuint declare() override {
if (!_id) {
glGenVertexArrays(1, &_id);
}
bind();
return _id;
}
}; };
class VertexError : public Error<VertexError> { class VertexError : public Error<VertexError> {
@@ -142,97 +127,5 @@ class VertexError : public Error<VertexError> {
}; };
using VBO = ArrayBuffer;
using VertBufVec = SharedVector<VBO>;
using EBO = ElementBuffer;
struct VertexData {
std::shared_ptr<VBO> vbo;
VertexAttributeList attrs;
};
using VertexDataVec = std::vector<VertexData>;
class VertexGroup {
protected:
using Codes = VertexError::Codes;
VertexDataVec _vertex_data;
std::shared_ptr<EBO> _ebo;
std::shared_ptr<VAO> _vao;
GLenum _primitive;
public:
GLenum primitive=GL_TRIANGLES;
VertexGroup(VertexGroup&&);
VertexGroup& operator=(VertexGroup&&);
VertexGroup(
const VertexDataVec& vertex_data,
const std::shared_ptr<EBO>& ebo
)
: _vao(std::make_shared<VAO>()), _ebo(ebo) {
setBuffers(vertex_data);
}
template<typename... T>
VertexGroup(
const VertexDataVec& vertex_data,
T... args
)
: VertexGroup(vertex_data, std::make_shared<EBO>(args...)) {
setBuffers(vertex_data);
}
template<typename... T>
VertexGroup(
const VertexData& vertex_data,
T... args
)
: VertexGroup(VertexDataVec{vertex_data}, args...) {}
template<typename... T>
VertexGroup(
const ByteVector& vertex_data,
const VertexAttributeList& vertex_specification,
T... args
) : VertexGroup({
std::make_shared<VBO>(vertex_data),
vertex_specification},
args...
) {}
void bind() const {
_vao->bind();
_ebo->bind();
}
void unbind() const {
_vao->unbind();
_ebo->unbind();
}
void draw() const;
VertexDataVec getBuffers();
VertexData getBuffers(size_t);
size_t setBuffers(const VertexDataVec&);
size_t addBuffer(const VertexData&);
size_t addBuffer(const ByteVector& data, const VertexAttributeList& attrs);
VertexDataVec dropBuffers();
VertexData dropBuffer(size_t);
VertexAttributePointer attribute(size_t) const;
void enableAttr(GLuint);
void disableAttr(GLuint);
void enableBuffer(size_t);
void disableBuffer(size_t);
void enable();
void disable();
std::shared_ptr<EBO> indices() const;
std::shared_ptr<EBO> indices(const std::vector<unsigned int>& data);
std::shared_ptr<EBO> indices(std::shared_ptr<EBO> buffer);
};
} // namespace nb } // namespace nb
#endif // _NB_VERTEX_ARRAY #endif // _NB_VERTEX_ARRAY
@@ -0,0 +1,43 @@
#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
+257 -49
View File
@@ -3,84 +3,292 @@
#define _NB_WINDOW #define _NB_WINDOW
#include <NBGraphics/GLLoad.hpp> #include <NBGraphics/GLLoad.hpp>
#include <NBGraphics/OGLObjects.hpp>
#include <array> #include <array>
#include <map> #include <functional>
#include <memory>
#include <string> #include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include <NBCore/Errors.hpp> #include <NBCore/Errors.hpp>
#include <NBCore/Utils.hpp> #include <NBCore/Utils.hpp>
namespace nb { namespace nb {
class OpenGLError : public Error<OpenGLError> { class GLFWError : public Error<GLFWError> {
using Base = Error<OpenGLError>; using Base = Error<GLFWError>;
public: public:
using Base::Base; using Base::Base;
enum Codes : unsigned int { enum Codes : unsigned int {
UNDEFINED, INIT_FAILED, GLFW_INTIALIZED, GLAD_FAILED UNDEFINED, INIT_FAILED, GLFW_INTIALIZED, GLAD_FAILED,
NOT_MAIN, WINDOW_FAILED
}; };
static const std::string type; static const std::string type;
static const ErrorCodeMap ErrorMessages; static const ErrorCodeMap ErrorMessages;
}; };
class WindowError : public Error<WindowError> { class OGLWindow;
using Base = Error<WindowError>;
public: enum WindowCallbacks {
using Base::Base; KEY, CHAR, CHAR_MODS, MOUSE_BUTTON, CURSOR_POS, CURSOR_ENTER,
SCROLL, DROP, WINDOW_POS, WINDOW_SIZE, WINDOW_CLOSE, WINDOW_REFRESH,
enum Codes : unsigned int { WINDOW_FOCUS, WINDOW_ICONIFY, WINDOW_MAX, FRAMEBUFFER_SIZE, WINDOW_SCALE,
UNDEFINED, INITIALIZED_WINDOW, NO_GLFW, INIT_FAILED
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
}; };
class Window { template<WindowCallbacks>
public: struct OGLWindowCallbacks;
static bool StrictInitialization;
static int getGLFWHint(int); template<>
static int setGLFWHint(int, int); struct OGLWindowCallbacks<WindowCallbacks::KEY> {
static Window* getCurrent(); 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)>;
};
Window(const std::array<uint16_t, 2>, const char*, GLFWmonitor* initMonitor=NULL, GLFWwindow* initWindow=NULL); class OGLWindow {
Window(const uint16_t, const uint16_t, const char*, GLFWmonitor* initMonitor=NULL, GLFWwindow* initWindow=NULL); using GLFWHint = std::array<int, 2>;
~Window(); private:
static inline void CheckForMainThread() {
if (nb::CurrentTID != nb::MainTID) {
THROW(GLFWError(GLFWError::Codes::NOT_MAIN));
}
}
int getWindowHint(int) const; protected:
GLFWwindow* getWindow() const; static std::atomic<unsigned int> _count;
std::array<uint16_t, 2> getSize() const; static std::atomic<bool> _glfwInitialized;
float getAspectRatio() const; static thread_local GLFWwindow* _currWindow;
std::string getName() const; static thread_local const GLFWwindow* _currArena;
int init(); template<typename T>
int setWindowHint(int, int); static void SetHint(std::pair<int, T> hint) {
void setCurrent(); if constexpr ( std::is_same_v<T, std::string> ) {
void resize(const std::array<uint16_t, 2>); glfwWindowHintString(std::get<0>(hint), std::get<1>(hint).c_str());
void resize(const uint16_t x, const uint16_t y); } else if constexpr ( std::is_same_v<T, int> ) {
glfwWindowHint(std::get<0>(hint), std::get<1>(hint));
}
}
protected: std::string _title;
static std::map<GLFWwindow*, Window*> WindowContexts; GLFWwindow* _window_ptr;
static std::map<int, int> GLFWHints; const GLFWwindow* _arena;
static Window* _current;
static bool _glfw_init;
static bool checkKillGLFW();
std::map<int, int> windowHints; OGLWindow(
std::array<uint16_t, 2> windowSize; unsigned int x,
float _aspect_ratio; unsigned int y,
std::string windowName; const std::string&,
GLFWwindow* window; GLFWwindow* sharingContext = NULL
GLFWmonitor* monitor; );
GLFWwindow* shareWindow;
bool _init = false; GLFWwindow* makeCurrent() const;
int gladResponse = -1; 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>&);
template <typename... T>
static std::shared_ptr<OGLWindow> CreateWindow(
unsigned int x,
unsigned int y,
const std::string& title,
const std::pair<int, T>&... windowHints
) {
(SetHint(std::pair(windowHints)),... );
return std::shared_ptr<OGLWindow>(new OGLWindow(
x,
y,
title,
nullptr
) );
}
template<typename... T>
static std::shared_ptr<OGLWindow> CreateSharedWindow(
unsigned int x,
unsigned int y,
const std::string& title,
std::shared_ptr<OGLWindow> sharingWindow = NULL,
const std::pair<int, T>&... windowHints
) {
(SetHint(std::pair(windowHints)),... );
return std::shared_ptr<OGLWindow>(new OGLWindow(
x,
y,
title,
sharingWindow->_window_ptr
) );
}
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.");
}
}
}; };
}; };
+37 -22
View File
@@ -2,7 +2,7 @@
namespace nb { namespace nb {
const std::unordered_map<GLenum, std::string> BufferTypes({ const ConstantMap<GLenum, std::string> BufferTypes({
{GL_ARRAY_BUFFER, "GL_ARRAY_BUFFER"}, {GL_ARRAY_BUFFER, "GL_ARRAY_BUFFER"},
{GL_ELEMENT_ARRAY_BUFFER, "GL_ELEMENT_BUFFER"} {GL_ELEMENT_ARRAY_BUFFER, "GL_ELEMENT_BUFFER"}
}); });
@@ -12,20 +12,31 @@ const std::string BufferError::type = "nb::BufferError";
const ErrorCodeMap BufferError::ErrorMessages = { const ErrorCodeMap BufferError::ErrorMessages = {
{ BufferErrorCodes::UNDEFINED, "Error" }, { BufferErrorCodes::UNDEFINED, "Error" },
{ BufferErrorCodes::DATA_OVERFLOW, "Attempting buffer overflow" }, { BufferErrorCodes::DATA_OVERFLOW, "Attempting buffer overflow" },
{BufferErrorCodes::DATA_ERROR, "Invalid memory operation"} { 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) { Buffer::Buffer(Buffer&& rval) : Target(rval.Target) {
*this = std::move(rval); *this = std::move(rval);
} }
Buffer& Buffer::operator=(Buffer&& rhs) { Buffer& Buffer::operator=(Buffer&& rhs) {
if (Target != rhs.Target) { if (Target != rhs.Target) {
auto targ_name = BufferTypes.at(Target); auto targ_name = BufferTypes[Target];
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ BufferType "+targ_name+" != BufferType "+BufferTypes.at(rhs.Target) "w/ BufferType "+targ_name+" != BufferType "+BufferTypes[Target]
)); ));
} }
OpenGLObject::operator=(std::move(rhs)); OpenGLObject::operator=(std::move(rhs));
@@ -44,13 +55,13 @@ size_t Buffer::size() const { return _size; }
ByteVector Buffer::data() const { ByteVector Buffer::data() const {
bind(); bind();
ByteVector ret(_size); ByteVector ret(_size);
glGetBufferSubData(Target, 0, _size, ret.data()); OPENGL_CALL(glGetBufferSubData(Target, 0, _size, ret.data()));
return ret; return ret;
} }
void Buffer::data(const void* data_, size_t size_, GLenum usage_) { void Buffer::data(const void* data_, size_t size_, GLenum usage_) {
declare(); declare();
glBufferData(Target, size_, data_, usage_); OPENGL_CALL(glBufferData(Target, size_, data_, usage_));
_size = size_; _size = size_;
_usage = usage_; _usage = usage_;
} }
@@ -65,7 +76,7 @@ void Buffer::subdata(const void* data_, size_t size_, GLintptr offset_) {
if (offset_+size_ <= _size) { if (offset_+size_ <= _size) {
THROW(BufferError(BufferError::Codes::DATA_OVERFLOW)); THROW(BufferError(BufferError::Codes::DATA_OVERFLOW));
} }
glBufferSubData(Target, offset_, size_, data_); OPENGL_CALL(glBufferSubData(Target, offset_, size_, data_));
} }
void Buffer::subdata(const ByteVector& data_, GLintptr offset_) { void Buffer::subdata(const ByteVector& data_, GLintptr offset_) {
@@ -74,17 +85,21 @@ void Buffer::subdata(const ByteVector& data_, GLintptr offset_) {
subdata(data_.data(), size_); subdata(data_.data(), size_);
} }
ElementBuffer::ElementBuffer() : Buffer(GL_ELEMENT_ARRAY_BUFFER) {} // class UniformBuffer
UniformBuffer::UniformBuffer() : Buffer(GL_UNIFORM_BUFFER) {}
ByteVector ElementBuffer::data() const { void UniformBuffer::bind() const {
return data(); Buffer::bind();
OPENGL_CALL(glBindBufferBase(GL_UNIFORM_BUFFER, _index, id()));
} }
size_t ElementBuffer::size() const { return _size / _typeSize; } GLuint UniformBuffer::bufferIndex() const { return _index; }
size_t ElementBuffer::typeSize() const { return _typeSize; } GLuint UniformBuffer::bufferIndex(GLuint idx) {
return (_index = idx);
}
GLenum ElementBuffer::glslType() const { return _glslType; } // class ElementBuffer
template void ElementBuffer::data<uint8_t>(const std::vector<uint8_t>& data, GLenum usage); 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<uint16_t>(const std::vector<uint16_t>& data, GLenum usage);
@@ -93,11 +108,11 @@ template void ElementBuffer::data<uint8_t>(const uint8_t* const data, size_t siz
template void ElementBuffer::data<uint16_t>(const uint16_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::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, size_t offset=0); 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, size_t 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, size_t 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, size_t 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, size_t 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, size_t offset=0); template void ElementBuffer::subdata<uint32_t>(const std::vector<uint32_t>& data, GLintptr offset=0);
} }
-307
View File
@@ -1,307 +0,0 @@
#include <NBGraphics/Draw.hpp>
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();
}
}
+86 -27
View File
@@ -11,7 +11,9 @@ const ErrorCodeMap FrameBufferError::ErrorMessages = {
GLuint FrameBufferBase::declare() { GLuint FrameBufferBase::declare() {
if (!_id) { if (!_id) {
glGenFramebuffers(1, &_id); OPENGL_CALL(
glGenFramebuffers(1, &_id)
);
} }
bind(); bind();
return _id; return _id;
@@ -20,7 +22,9 @@ GLuint FrameBufferBase::declare() {
void FrameBufferBase::remove() { void FrameBufferBase::remove() {
if (_id) { if (_id) {
unbind(); unbind();
glDeleteFramebuffers(1, &_id); OPENGL_CALL(
glDeleteFramebuffers(1, &_id)
);
_id=0; _id=0;
} }
} }
@@ -31,7 +35,9 @@ std::shared_ptr<RenderTarget> FrameBufferBase::detach(GLenum attch_) {
bind(); bind();
auto ret = _attachments.at(attch_); auto ret = _attachments.at(attch_);
_attachments.erase(attch_); _attachments.erase(attch_);
glFramebufferTexture(Target, attch_, 0, 0); OPENGL_CALL(
glFramebufferTexture(Target, attch_, 0, 0)
);
return ret; return ret;
} }
@@ -47,13 +53,13 @@ void FrameBufferBase::attach(
"Cannot attach object to `GL_NONE`" "Cannot attach object to `GL_NONE`"
)); ));
} }
glFramebufferTextureLayer( OPENGL_CALL(glFramebufferTextureLayer(
Target, Target,
attachment_, attachment_,
texture_->id(), texture_->id(),
level_, level_,
layer_ layer_
); ));
_attachments[attachment_] = texture_; _attachments[attachment_] = texture_;
} }
@@ -69,43 +75,72 @@ void FrameBufferBase::attach(
)); ));
} }
if (texTypeIs2D(texture_->Target)) { if (texTypeIs2D(texture_->Target)) {
glFramebufferTexture2D( OPENGL_CALL(glFramebufferTexture2D(
Target, Target,
attachment_, attachment_,
texture_->Target, texture_->Target,
texture_->id(), texture_->id(),
level_ level_
); ));
} else { } else {
glFramebufferTexture1D( OPENGL_CALL(glFramebufferTexture1D(
Target, Target,
attachment_, attachment_,
texture_->Target, texture_->Target,
texture_->id(), texture_->id(),
level_ level_
); ));
} }
_attachments[attachment_] = texture_; _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 { void FrameBufferBase::bind() const {
if (_id) { if (_id) {
glBindFramebuffer(Target, _id); OPENGL_CALL(
glBindFramebuffer(Target, _id)
);
} else { } else {
THROW(OGLError( THROW(OpenGLObjectError(
OGLError::Codes::INVALID_OBJECT, OpenGLObjectError::Codes::INVALID_OBJECT,
"w/ FrameBuffer" "w/ FrameBuffer"
)); ));
} }
} }
void FrameBufferBase::unbind() const { void FrameBufferBase::unbind() const {
glBindFramebuffer(Target, 0); OPENGL_CALL(
glBindFramebuffer(Target, 0)
);
} }
GLenum FrameBufferBase::status() const { GLenum FrameBufferBase::status() const {
bind(); bind();
return glCheckFramebufferStatus(Target); return OPENGL_CALL(
glCheckFramebufferStatus(Target)
);
}
bool FrameBufferBase::complete() const {
return status() == GL_FRAMEBUFFER_COMPLETE;
} }
FrameBufferBase::AttachmentMap FrameBufferBase::getAllBuffers() const { FrameBufferBase::AttachmentMap FrameBufferBase::getAllBuffers() const {
@@ -166,7 +201,7 @@ std::shared_ptr<RenderTarget> ReadFrameBuffer::setReadBuffer(GLenum attch_) {
} }
} }
_location = attch_; _location = attch_;
glReadBuffer(_location); OPENGL_CALL(glReadBuffer(_location));
return getReadBuffer(); return getReadBuffer();
} }
@@ -222,7 +257,9 @@ WriteFrameBuffer::DrawTexVec WriteFrameBuffer::setWriteBuffers(const std::vector
} }
} }
_locations = attchs_; _locations = attchs_;
glDrawBuffers(_locations.size(), _locations.data()); OPENGL_CALL(
glDrawBuffers(_locations.size(), _locations.data())
);
return getWriteBuffers(); return getWriteBuffers();
} }
@@ -230,7 +267,9 @@ std::shared_ptr<Texture> WriteFrameBuffer::setWriteBuffer(GLenum attch_) {
bind(); bind();
if (attch_ == GL_NONE) { if (attch_ == GL_NONE) {
std::vector<GLenum> tmp(_locations.size(), GL_NONE); std::vector<GLenum> tmp(_locations.size(), GL_NONE);
glDrawBuffers(tmp.size(), tmp.data()); OPENGL_CALL(
glDrawBuffers(tmp.size(), tmp.data())
);
_locations = {}; _locations = {};
return nullptr; return nullptr;
} }
@@ -241,13 +280,17 @@ std::shared_ptr<Texture> WriteFrameBuffer::setWriteBuffer(GLenum attch_) {
fRGBA WriteFrameBuffer::clearColorValue() const { fRGBA WriteFrameBuffer::clearColorValue() const {
bind(); bind();
float rgba[4]; float rgba[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); OPENGL_CALL(
glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba)
);
return fRGBA{rgba[0], rgba[1], rgba[2], rgba[3]}; return fRGBA{rgba[0], rgba[1], rgba[2], rgba[3]};
} }
fRGBA WriteFrameBuffer::clearColorValue(const fRGBA& color) { fRGBA WriteFrameBuffer::clearColorValue(const fRGBA& color) {
declare(); declare();
glClearColor(color.r, color.g, color.b, color.a); OPENGL_CALL(
glClearColor(color.r, color.g, color.b, color.a)
);
return color; return color;
} }
@@ -258,32 +301,42 @@ fRGBA WriteFrameBuffer::clearColorValue(float r, float g, float b, float a) {
double WriteFrameBuffer::clearDepthValue() const { double WriteFrameBuffer::clearDepthValue() const {
bind(); bind();
double ret; double ret;
glGetDoublev(GL_DEPTH_CLEAR_VALUE, &ret); OPENGL_CALL(
glGetDoublev(GL_DEPTH_CLEAR_VALUE, &ret)
);
return ret; return ret;
} }
double WriteFrameBuffer::clearDepthValue(double d_) { double WriteFrameBuffer::clearDepthValue(double d_) {
declare(); declare();
glClearDepth(d_); OPENGL_CALL(
glClearDepth(d_)
);
return d_; return d_;
} }
GLint WriteFrameBuffer::clearStencilValue() const { GLint WriteFrameBuffer::clearStencilValue() const {
bind(); bind();
GLint ret; GLint ret;
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &ret); OPENGL_CALL(
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &ret)
);
return ret; return ret;
} }
GLint WriteFrameBuffer::clearStencilValue(GLint s_) { GLint WriteFrameBuffer::clearStencilValue(GLint s_) {
declare(); declare();
glClearStencil(s_); OPENGL_CALL(
glClearStencil(s_)
);
return s_; return s_;
} }
void WriteFrameBuffer::clear(GLbitfield mask_) const { void WriteFrameBuffer::clear(GLbitfield mask_) const {
bind(); bind();
glClear(mask_); OPENGL_CALL(
glClear(mask_)
);
} }
void WriteFrameBuffer::clearDepth() const { void WriteFrameBuffer::clearDepth() const {
@@ -292,7 +345,9 @@ void WriteFrameBuffer::clearDepth() const {
void WriteFrameBuffer::clearDepth(float val_) const { void WriteFrameBuffer::clearDepth(float val_) const {
bind(); bind();
glClearBufferfv(GL_DEPTH, 0, &val_); OPENGL_CALL(
glClearBufferfv(GL_DEPTH, 0, &val_)
);
} }
void WriteFrameBuffer::clearStencil() const { void WriteFrameBuffer::clearStencil() const {
@@ -301,7 +356,9 @@ void WriteFrameBuffer::clearStencil() const {
void WriteFrameBuffer::clearStencil(GLint val_) const { void WriteFrameBuffer::clearStencil(GLint val_) const {
bind(); bind();
glClearBufferiv(GL_STENCIL, 0, &val_); OPENGL_CALL(
glClearBufferiv(GL_STENCIL, 0, &val_)
);
} }
void WriteFrameBuffer::clearDepthStencil() const { void WriteFrameBuffer::clearDepthStencil() const {
@@ -310,7 +367,9 @@ void WriteFrameBuffer::clearDepthStencil() const {
void WriteFrameBuffer::clearDepthStencil(float d_, GLint s_) const { void WriteFrameBuffer::clearDepthStencil(float d_, GLint s_) const {
bind(); bind();
glClearBufferfi(GL_DEPTH_STENCIL, 0, d_, s_); OPENGL_CALL(
glClearBufferfi(GL_DEPTH_STENCIL, 0, d_, s_)
);
} }
FrameBuffer::FrameBuffer() FrameBuffer::FrameBuffer()
+73
View File
@@ -0,0 +1,73 @@
#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
+83 -7
View File
@@ -1,23 +1,99 @@
#include <NBGraphics/OGLObjects.hpp> #include <NBGraphics/OGLObjects.hpp>
#include <NBGraphics/Window.hpp>
#ifndef GLENUMSTRPAIR
#define GLENUMSTRPAIR(x) {x, #x}
#endif // GLENUMSTRPAIR
namespace nb { namespace nb {
const std::string OGLError::type = "nb::OGLError"; const std::string OpenGLObjectError::type = "nb::OpenGLObjectError";
const ErrorCodeMap OGLError::ErrorMessages = { const ErrorCodeMap OpenGLObjectError::ErrorMessages = {
{ OGLError::Codes::UNDEFINED, "Error" }, { OpenGLObjectError::Codes::UNDEFINED, "Error" },
{OGLError::Codes::HANGING_OBJECT, "Attempting to leave a hanging OpenGL object"}, {OpenGLObjectError::Codes::HANGING_OBJECT, "Attempting to leave a hanging OpenGL object"},
{OGLError::Codes::INVALID_OBJECT, "Attempting operation with invalid object"} {OpenGLObjectError::Codes::INVALID_OBJECT, "Attempting operation with invalid object"},
{OpenGLObjectError::Codes::INVALID_CONTEXT, "Object not valid with current OpengGL context"}
}; };
OpenGLObject::OpenGLObject(OpenGLObject&& rval) { 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); *this = std::move(rval);
} }
OpenGLObject::OpenGLObject() : _arena(OGLWindow::GetCurrentObjectArena()) {}
OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) { OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) {
if (_id) { THROW(OGLError(Codes::HANGING_OBJECT)); } rhs.checkObjectContextValidity();
if (_id) { THROW(OpenGLObjectError(Codes::HANGING_OBJECT)); }
_id = rhs._id; _id = rhs._id;
rhs._id = 0; rhs._id = 0;
return *this; 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 } // namespace nb
+30 -6
View File
@@ -15,6 +15,8 @@ const ErrorCodeMap ProgramError::ErrorMessages = {
{ProgramErrCodes::LINKING_ERROR, "Linker error"} {ProgramErrCodes::LINKING_ERROR, "Linker error"}
}; };
// class Shader
Shader::Shader(GLenum target_, const std::string& source_) Shader::Shader(GLenum target_, const std::string& source_)
: Shader(target_, std::vector<std::string>({source_})) {} : Shader(target_, std::vector<std::string>({source_})) {}
@@ -41,25 +43,27 @@ bool Shader::success() const {
GLint Shader::status(GLenum parameter) const { GLint Shader::status(GLenum parameter) const {
GLint param = 0; GLint param = 0;
glGetShaderiv(_id, parameter, &param); OPENGL_CALL(glGetShaderiv(_id, parameter, &param));
return param; return param;
} }
std::string Shader::log() const { std::string Shader::log() const {
GLint logsize = status(GL_INFO_LOG_LENGTH); GLint logsize = status(GL_INFO_LOG_LENGTH);
char* log_ = new char[logsize]; char* log_ = new char[logsize];
glGetShaderInfoLog(_id, logsize, NULL, log_); OPENGL_CALL(glGetShaderInfoLog(_id, logsize, NULL, log_));
std::string ret(log_, logsize); std::string ret(log_, logsize);
delete[] log_; delete[] log_;
return ret; return ret;
} }
// class Program
Program::Program(SharedVector<Shader> shaders_) { Program::Program(SharedVector<Shader> shaders_) {
declare(); declare();
for (auto shad_ptr : shaders_) { for (auto shad_ptr : shaders_) {
glAttachShader(_id, shad_ptr->id()); OPENGL_CALL(glAttachShader(_id, shad_ptr->id()));
} }
glLinkProgram(_id); OPENGL_CALL(glLinkProgram(_id));
_success = status(GL_LINK_STATUS); _success = status(GL_LINK_STATUS);
if (!_success) { if (!_success) {
WARN(log(), 0x0FE); WARN(log(), 0x0FE);
@@ -70,19 +74,39 @@ Program::operator bool() { return _success; }
GLint Program::status(GLenum parameter) const { GLint Program::status(GLenum parameter) const {
GLint param = 0; GLint param = 0;
glGetProgramiv(_id, parameter, &param); OPENGL_CALL(glGetProgramiv(_id, parameter, &param));
return param; return param;
} }
std::string Program::log() const { std::string Program::log() const {
GLint logsize = status(GL_INFO_LOG_LENGTH); GLint logsize = status(GL_INFO_LOG_LENGTH);
char* log_ = new char[logsize]; char* log_ = new char[logsize];
glGetProgramInfoLog(_id, logsize, NULL, log_); OPENGL_CALL(glGetProgramInfoLog(_id, logsize, NULL, log_));
std::string ret(log_, logsize); std::string ret(log_, logsize);
delete[] log_; delete[] log_;
return ret; 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);
}
} }
+27
View File
@@ -2,6 +2,33 @@
namespace nb { 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(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 } // namespace nb
+50 -175
View File
@@ -1,3 +1,6 @@
#pragma clang diagnostic ignored "-Wint-to-pointer-cast"
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
#include <NBGraphics/VertexArray.hpp> #include <NBGraphics/VertexArray.hpp>
namespace nb { namespace nb {
@@ -16,7 +19,7 @@ const ErrorCodeMap VertexError::ErrorMessages = {
{ VertexError::MISALIGNED_DATA, "Data does not match vertex layout"} { VertexError::MISALIGNED_DATA, "Data does not match vertex layout"}
}; };
VAO::VAO(const VertexAttributePointerList& attr_ptrs) { VAO::VAO(const VertexDataPointerList& attr_ptrs) {
attributes(attr_ptrs); attributes(attr_ptrs);
} }
@@ -26,41 +29,58 @@ VAO::VAO(VAO&& other) {
VAO& VAO::operator=(VAO&& rhs) { VAO& VAO::operator=(VAO&& rhs) {
OpenGLObject::operator=(std::move(rhs)); OpenGLObject::operator=(std::move(rhs));
_attrs = rhs._attrs; _vertexdata = rhs._vertexdata;
rhs._attrs = {}; rhs._vertexdata = {};
return *this; return *this;
} }
VertexAttributePointerList VAO::attributes() const { VertexDataPointerList VAO::attributes() const {
return _attrs; return _vertexdata;
} }
VertexAttributePointerList VAO::attributes(const VertexAttributePointerList& attrs_) { VertexDataPointerList VAO::attributes(const VertexDataPointerList& vertdatalist) {
declare(); declare();
disable(); disable();
_attrs = attrs_; _vertexdata = vertdatalist;
bind(); bind();
for (auto attr_ptr : attrs_) { for (const auto vdata : _vertexdata) {
glBindBuffer(GL_ARRAY_BUFFER, attr_ptr.buffer); OPENGL_CALL(glBindBuffer(GL_ARRAY_BUFFER, vdata.vertexdata->data->id()));
GLuint idx = attr_ptr.index; for (const auto attr : vdata.vertexdata->attributes) {
glVertexAttribPointer( GLuint idx = vdata.index;
idx, OPENGL_CALL(glVertexAttribPointer(
attr_ptr.attribute.GLSLSize, idx,
attr_ptr.attribute.GLSLType, attr.size,
attr_ptr.attribute.GLSLNormalization, TypeToGLSL[attr.type],
attr_ptr.attribute.layout.stride, attr.normalized,
(void*)attr_ptr.attribute.layout.offset attr.layout.stride,
); (const void*) attr.layout.offset
glEnableVertexAttribArray(idx); ));
OPENGL_CALL(glEnableVertexAttribArray(idx));
if (attr.layout.divisor) {
OPENGL_CALL(glVertexAttribDivisor(idx, attr.layout.divisor));
}
}
} }
unbind(); unbind();
return _attrs; enable();
return _vertexdata;
} }
VertexAttributePointer VAO::attr(GLuint idx) const { VertexDataPointerList VAO::attributes(const VertexDataList& vertdatalist) {
for (auto attr_ptr : _attrs) { VertexDataPointerList vdatas;
if (idx == attr_ptr.index) { for (unsigned int i = 0; i < vertdatalist.size(); ++i) {
return attr_ptr; 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)); THROW(VAOError(Codes::INVALID_ATTRIBUTE));
@@ -69,8 +89,8 @@ VertexAttributePointer VAO::attr(GLuint idx) const {
void VAO::enable() const { void VAO::enable() const {
if (_id) { if (_id) {
bind(); bind();
for(auto attr_ptr : _attrs) { for(auto vdata : _vertexdata) {
glEnableVertexAttribArray(attr_ptr.index); OPENGL_CALL(glEnableVertexAttribArray(vdata.index));
} }
unbind(); unbind();
} }
@@ -79,7 +99,7 @@ void VAO::enable() const {
void VAO::enable(GLuint idx) const { void VAO::enable(GLuint idx) const {
if(_id) { if(_id) {
bind(); bind();
glEnableVertexAttribArray(attr(idx).index); OPENGL_CALL(glEnableVertexAttribArray(attribute(idx).index));
unbind(); unbind();
} }
} }
@@ -87,8 +107,8 @@ void VAO::enable(GLuint idx) const {
void VAO::disable() const { void VAO::disable() const {
if(_id) { if(_id) {
bind(); bind();
for(auto attr_ptr : _attrs) { for(auto vdata : _vertexdata) {
glDisableVertexAttribArray(attr_ptr.index); OPENGL_CALL(glDisableVertexAttribArray(vdata.index));
} }
unbind(); unbind();
} }
@@ -97,155 +117,10 @@ void VAO::disable() const {
void VAO::disable(GLuint idx) const { void VAO::disable(GLuint idx) const {
if(_id) { if(_id) {
bind(); bind();
glDisableVertexAttribArray(attr(idx).index); OPENGL_CALL(glDisableVertexAttribArray(attribute(idx).index));
unbind(); unbind();
} }
} }
VertexGroup::VertexGroup(VertexGroup&& other) {
*this = std::move(other);
}
VertexGroup& VertexGroup::operator=(VertexGroup&& rhs) {
_vertex_data = rhs._vertex_data;
_ebo = rhs._ebo;
_vao = rhs._vao;
rhs._vertex_data = {};
rhs._ebo = nullptr;
rhs._vao = nullptr;
return *this;
}
void VertexGroup::draw() const {
bind();
glDrawElements(primitive, _ebo->size(), _ebo->glslType(), 0);
}
size_t VertexGroup::addBuffer(const VertexData& vertex_data_) {
VertexData data = vertex_data_;
_vertex_data.emplace_back(data);
VertexAttributePointerList attrs = _vao->attributes();
GLuint idx = attrs.size();
for (const auto& attr : data.attrs) {
attrs.emplace_back(
VertexAttributePointer{attr, data.vbo->id(),idx}
);
idx++;
}
_vao->attributes(attrs);
return _vertex_data.size();
}
size_t VertexGroup::addBuffer(const ByteVector& data_, const VertexAttributeList& attrs_) {
return addBuffer({
std::make_shared<VBO>(data_),
attrs_
});
}
VertexData VertexGroup::getBuffers(size_t idx) {
return _vertex_data[idx];
}
VertexDataVec VertexGroup::getBuffers() {
return _vertex_data;
}
size_t VertexGroup::setBuffers(const VertexDataVec& vertex_data_) {
_vertex_data = vertex_data_;
VertexAttributePointerList attr_ptrs;
GLuint idx = 0;
for (const auto& data : _vertex_data) {
for (const auto& attr : data.attrs) {
attr_ptrs.emplace_back(
VertexAttributePointer{attr, data.vbo->id(), idx}
);
idx++;
}
}
_vao->attributes(attr_ptrs);
return _vertex_data.size();
}
VertexDataVec VertexGroup::dropBuffers() {
auto ret = _vertex_data;
setBuffers({});
return ret;
}
VertexData VertexGroup::dropBuffer(size_t idx) {
if (idx >= _vertex_data.size()) {
THROW(Error(Error<>::INDEX_ERROR));
}
VertexDataVec tmp;
VertexData ret;
size_t i = 0;
for (auto buf : _vertex_data) {
if (i == idx) {
ret = tmp[idx];
} else {
tmp.emplace_back(buf);
}
i++;
}
setBuffers(tmp);
return ret;
}
VertexAttributePointer VertexGroup::attribute(size_t idx_) const {
return _vao->attr(idx_);
}
void VertexGroup::enableAttr(GLuint idx) {
bind();
_vao->enable(idx);
unbind();
}
void VertexGroup::disableAttr(GLuint idx) {
bind();
_vao->disable(idx);
unbind();
}
void VertexGroup::disableBuffer(size_t idx) {
auto buf_idx = _vertex_data[idx].vbo->id();
bind();
for (auto attr : _vao->attributes()) {
if (attr.buffer == buf_idx) {
_vao->disable(attr.index);
}
}
unbind();
}
void VertexGroup::enableBuffer(size_t idx) {
auto buf_idx = _vertex_data[idx].vbo->id();
bind();
for (auto attr : _vao->attributes()) {
if (attr.buffer == buf_idx) {
_vao->enable(attr.index);
}
}
unbind();
}
void VertexGroup::enable() { _vao->enable(); }
void VertexGroup::disable() { _vao->disable(); }
std::shared_ptr<EBO> VertexGroup::indices() const { return _ebo; }
std::shared_ptr<EBO> VertexGroup::indices(const std::vector<uint32_t>& data) {
_ebo->data(data);
return _ebo;
}
std::shared_ptr<EBO> VertexGroup::indices(std::shared_ptr<EBO> buffer) {
_ebo = buffer;
return _ebo;
}
} // namespace nb } // namespace nb
+16
View File
@@ -0,0 +1,16 @@
#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
+111 -142
View File
@@ -2,181 +2,150 @@
namespace nb { namespace nb {
std::map<GLFWwindow*, Window*> Window::WindowContexts = {}; using GLFWCodes = GLFWError::Codes;
std::map<int, int> Window::GLFWHints = {}; const std::string GLFWError::type = "nb::GLFWError";
bool Window::StrictInitialization = true; const ErrorCodeMap GLFWError::ErrorMessages = {
bool Window::_glfw_init = false; {GLFWCodes::UNDEFINED, "Error"},
Window* Window::_current = nullptr; {GLFWCodes::INIT_FAILED, "GLFW initialization failed"},
static std::map<int, int> defailt_window_hints = { {GLFWCodes::GLFW_INTIALIZED, "GLFW has already been initialized"},
{GLFW_CONTEXT_VERSION_MAJOR, 3}, {GLFWCodes::GLAD_FAILED, "GLAD initialization failed"},
{GLFW_CONTEXT_VERSION_MINOR, 1}, {GLFWCodes::NOT_MAIN, "Action can only be done on main thread"},
{GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE} {GLFWCodes::WINDOW_FAILED, "Failed to initialize window"}
#ifdef _NB_GL_DEBUG_ON
, {GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE}
#endif
}; };
using OpenGLErrorCodes = OpenGLError::Codes; // class OGLWindow
const std::string OpenGLError::type = "nb::OpenGLError";
const ErrorCodeMap OpenGLError::ErrorMessages = {
{OpenGLErrorCodes::UNDEFINED, "Error"},
{OpenGLErrorCodes::INIT_FAILED, "GLFW initialization failed"},
{OpenGLErrorCodes::GLFW_INTIALIZED, "GLFW has already been initialized"},
{OpenGLErrorCodes::GLAD_FAILED, "GLAD initialization failed"}
};
using WindowErrorCodes = WindowError::Codes; std::atomic<bool> OGLWindow::_glfwInitialized = false;
const std::string WindowError::type = "nb::WindowError"; thread_local GLFWwindow* OGLWindow::_currWindow = nullptr;
const ErrorCodeMap WindowError::ErrorMessages = { thread_local const GLFWwindow* OGLWindow::_currArena = nullptr;
{WindowErrorCodes::UNDEFINED, "Error"}, std::atomic<unsigned int> OGLWindow::_count = 0;
{WindowErrorCodes::INITIALIZED_WINDOW, "Window already initialized"},
{WindowErrorCodes::NO_GLFW, "GLFW has not been initialized"},
{WindowErrorCodes::INIT_FAILED, "Could not intialized window"}
};
int Window::getGLFWHint(int hint_key) { bool OGLWindow::InitGLFW(const std::vector<GLFWHint>& hints) {
if (GLFWHints.find(hint_key) == GLFWHints.end()) { if (nb::MainTID != GetTID()) {
return 0; THROW(GLFWError(GLFWError::NOT_MAIN));
} else {
return GLFWHints.at(hint_key);
} }
} if (!IsGLFWInitialized()) {
for (const auto& hint : hints) {
int Window::setGLFWHint(int hint_key, int hint_val) { glfwInitHint(hint[0], hint[1]);
if (Window::_glfw_init) {
THROW(OpenGLError(OpenGLErrorCodes::GLFW_INTIALIZED));
} else {
GLFWHints[hint_key] = hint_val;
}
return GLFWHints[hint_key];
}
Window* Window::getCurrent() {
return _current;
}
bool Window::checkKillGLFW() {
if(Window::WindowContexts.size() == 0 && _glfw_init) {
glfwTerminate();
Window::_glfw_init = false;
return true;
}
return false;
}
Window::Window(const uint16_t x, const uint16_t y, const char* initName, GLFWmonitor* initMonitor, GLFWwindow* initWindow) {
if (!Window::_glfw_init) {
for (const auto& hint : Window::GLFWHints) {
glfwInitHint(hint.first, hint.second);
} }
int glfwResponse = glfwInit(); if (glfwInit()) {
if (glfwResponse) { OGLWindow::_glfwInitialized.store(true, std::memory_order_release);
Window::_glfw_init = true;
} else { } else {
if (Window::StrictInitialization) { THROW(GLFWError(GLFWError::INIT_FAILED));
THROW(OpenGLError(OpenGLErrorCodes::INIT_FAILED));
}
} }
} }
return IsGLFWInitialized();
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;
}
} }
Window::Window(const std::array<uint16_t, 2> initSize, const char* initName, GLFWmonitor* initMonitor, GLFWwindow* initWindow) : bool OGLWindow::TerminateGLFW() {
Window(initSize[0], initSize[1], initName, initMonitor, initWindow){} if (nb::MainTID != GetTID()) {
THROW(GLFWError(GLFWError::NOT_MAIN));
Window::~Window() { }
glfwSetWindowShouldClose(window, true); if (IsGLFWInitialized()) {
glfwDestroyWindow(window);
Window::WindowContexts.erase(window);
if (Window::WindowContexts.size()==0) {
glfwTerminate(); glfwTerminate();
OGLWindow::_glfwInitialized.store(false, std::memory_order_release);
} }
return !IsGLFWInitialized();
} }
void Window::setCurrent() { GLFWwindow* OGLWindow::MakeCurrent(const std::shared_ptr<OGLWindow>& window) {
_current = this; auto tmp = _currWindow;
glfwMakeContextCurrent(window); if (window) {
} _currWindow = window->getWindowPtr();
_currArena = window->_arena;
int Window::getWindowHint(int hint_key) const {
if (windowHints.find(hint_key) == windowHints.end()) {
return 0;
} else { } else {
return windowHints.at(hint_key); _currWindow = nullptr;
_currArena = nullptr;
} }
glfwMakeContextCurrent(_currWindow);
return tmp;
} }
int Window::setWindowHint(int hint_key, int hint_val) { OGLWindow::OGLWindow(
if (_init) { unsigned int x,
THROW(WindowError(WindowErrorCodes::INITIALIZED_WINDOW)); unsigned int y,
} else { const std::string&,
windowHints[hint_key] = hint_val; GLFWwindow* sharingContext
) {
CheckForMainThread();
InitGLFW();
_window_ptr = glfwCreateWindow(
x,
y,
_title.c_str(),
NULL,
sharingContext
);
if (_window_ptr == NULL) {
THROW(GLFWError(GLFWError::Codes::WINDOW_FAILED));
} }
return windowHints[hint_key]; _arena = _window_ptr;
auto tmp = makeCurrent();
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
THROW(GLFWError(GLFWError::Codes::GLAD_FAILED));
}
glfwMakeContextCurrent(tmp);
OGLWindow::_count.fetch_add(1);
} }
int Window::init() { OGLWindow::~OGLWindow() {
if (!_glfw_init) { CheckForMainThread();
THROW(WindowError(WindowErrorCodes::NO_GLFW)); if (_window_ptr) {
} if (_window_ptr == _currWindow) {
for (const auto& hint : windowHints) { _currWindow = nullptr;
glfwWindowHint(hint.first, hint.second); _currArena = nullptr;
} }
glfwDestroyWindow(_window_ptr);
window = glfwCreateWindow(windowSize[0], windowSize[1], windowName.c_str(), monitor, shareWindow); _count.fetch_add(-1);
if (window == NULL) { if (!_count.load()) {
Window::WindowContexts.erase(window); TerminateGLFW();
if (Window::WindowContexts.size()==0 && Window::_glfw_init) { glfwTerminate(); }
if (Window::StrictInitialization) {
THROW(WindowError(WindowErrorCodes::INIT_FAILED));
} }
} }
glfwMakeContextCurrent(window);
Window::WindowContexts[window] = this;
gladResponse = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
if (!gladResponse) {
Window::checkKillGLFW();
if (Window::StrictInitialization) {
THROW(OpenGLError(OpenGLErrorCodes::GLAD_FAILED));
}
}
_init = true;
glViewport(0, 0, windowSize[0], windowSize[1]);
return gladResponse;
} }
GLFWwindow* Window::getWindow() const { void OGLWindow::detachWindow() {
return window; _title = "";
_window_ptr = nullptr;
_arena = nullptr;
} }
float Window::getAspectRatio() const { return _aspect_ratio; } int OGLWindow::getWindowAttribute(int attr) const {
CheckForMainThread();
std::array<uint16_t, 2> Window::getSize() const { return glfwGetWindowAttrib(_window_ptr, attr);
return windowSize;
} }
std::string Window::getName() const { std::array<int, 2> OGLWindow::getSize() const {
return windowName; CheckForMainThread();
int x, y;
glfwGetWindowSize(_window_ptr, &x, &y);
return {x, y};
} }
void Window::resize(const std::array<uint16_t, 2> newSize) { bool OGLWindow::shouldClose() const {
windowSize = newSize; CheckForMainThread();
_aspect_ratio = float(newSize[0]) / float(newSize[1]); return glfwWindowShouldClose(_window_ptr);
glViewport(0, 0, windowSize[0], windowSize[1]);
glfwSetWindowSize(window, windowSize[0], windowSize[1]);
} }
void Window::resize(const uint16_t x, const uint16_t y) { resize({x, y}); } void OGLWindow::shouldClose(bool val) {
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());
}
}; };
+9 -1
View File
@@ -4,21 +4,29 @@ if (NB_BUILD_TESTS)
enable_testing() enable_testing()
include(GoogleTest) include(GoogleTest)
set(STBIMAGE_PATH ${NBENGINE_ROOT}/../stbi_image)
get_filename_component(STBIMAGE_PATH ${STBIMAGE_PATH} ABSOLUTE)
add_executable(TestWindow add_executable(TestWindow
./TestWindow.cpp ./TestWindow.cpp
) )
target_link_libraries(TestWindow target_link_libraries(TestWindow
NBGraphics NBGraphics
) )
target_include_directories(TestWindow
PRIVATE "${STBIMAGE_PATH}"
)
add_executable(TestImages add_executable(TestImages
./testImages.cpp ./testImages.cpp
) )
target_link_libraries(TestImages target_link_libraries(TestImages
NBCore
NBGraphics NBGraphics
GTest::gtest_main GTest::gtest_main
) )
target_include_directories(TestImages
PRIVATE "${STBIMAGE_PATH}"
)
gtest_discover_tests(TestImages) gtest_discover_tests(TestImages)
+45 -57
View File
@@ -2,29 +2,37 @@
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" #include "stb_image.h"
#include <NBCore/Errors.hpp>
#include <NBCore/TypeTraits.hpp>
#include <NBGraphics/Image.hpp> #include <NBGraphics/Image.hpp>
#include <NBGraphics/Mesh.hpp>
#include <NBGraphics/ProgramPipeline.hpp> #include <NBGraphics/ProgramPipeline.hpp>
#include <NBGraphics/VertexArray.hpp> #include <NBGraphics/VertexData.hpp>
#include <NBGraphics/Window.hpp> #include <NBGraphics/Window.hpp>
#include <NBGraphics/Textures.hpp> #include <NBGraphics/Textures.hpp>
int main() { int main() {
nb::logger.log("Howdy!"); LOG("Howdy!");
nb::Window window(400, 400, "Hello!"); auto window = nb::OGLWindow::CreateWindow(
window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 400,
window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); 400,
window.init(); "Howdy!",
nb::KeyVal(GLFW_CONTEXT_VERSION_MAJOR, 3),
nb::KeyVal(GLFW_CONTEXT_VERSION_MINOR, 3)
);
nb::OGLWindow::MakeCurrent(window);
auto vert = std::make_shared<nb::Shader>( auto vert = std::make_shared<nb::Shader>(
GL_VERTEX_SHADER, GL_VERTEX_SHADER,
"#version 330 core\n" "#version 330 core\n"
"layout (location = 0) in vec2 aPos;\n" "layout (location = 0) in vec2 aPos;\n"
"layout (location = 1) in vec2 tPos;\n" "out vec4 vColor;\n"
"out vec2 vPos;\n"
"void main()\n" "void main()\n"
"{\n" "{\n"
" gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);\n" " gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);\n"
" vPos = tPos;\n" " vec2 tmp = (aPos+vec2(1.0, 1.0))*0.5;\n"
" vColor = vec4(tmp.x, 0, tmp.y, 1.0);\n"
"}\0" "}\0"
); );
@@ -33,74 +41,54 @@ int main() {
auto frag = std::make_shared<nb::Shader>( auto frag = std::make_shared<nb::Shader>(
GL_FRAGMENT_SHADER, GL_FRAGMENT_SHADER,
"#version 330 core\n" "#version 330 core\n"
"in vec2 vPos;\n" "in vec4 vColor;\n"
"out vec4 FragColor;\n" "out vec4 FragColor;\n"
"uniform sampler2D tex;\n"
"void main()\n" "void main()\n"
"{\n" "{\n"
" FragColor = texture(tex, vPos);\n" " FragColor = vColor;\n"
"}\n\0" "}\n\0"
); );
LOG(frag->log()); LOG(frag->log());
nb::ByteVector data = nb::vectorToBytes<float>({ nb::ByteVector data = nb::vectorToBytes<float>({
-0.5, -0.5, 0,0, -0.5, -0.5,
-0.5, 0.5, 0,1, 0, 0.5,
0.5, 0.5, 1,1, 0.5, -0.5
0.5, -0.5, 1,0
}); });
nb::Program prog({vert, frag}); nb::Program prog({vert, frag});
prog.bind(); prog.bind();
std::vector<uint32_t> indxs = {0, 1, 2, 0, 2, 3}; std::vector<uint32_t> indxs = {0, 1, 2};
nb::VertexGroup tri(data, { nb::IndexedMesh tri(GL_TRIANGLES, data, {nb::VertexAttribute{
nb::VertexAttribute{
2, 2,
GL_FLOAT, nb::TypeCodes::FLOAT32,
false, false,
{0, 16} {0, 8}
}, }}, indxs);
nb::VertexAttribute{
2,
GL_FLOAT,
false,
{8, 16}
}
}, indxs);
tri.bind();
int width, height, numChannels;
auto raw_img_data = stbi_load(
"./awesomeface.png",
&width,
&height,
&numChannels,
0
);
LOG(numChannels);
using RGBA = nb::Pixel<uint8_t, nb::Red, nb::Green, nb::Blue, nb::Alpha>;
nb::ImageReference<RGBA> img(width, height, raw_img_data);
auto tex = nb::ImageTexture<RGBA>();
tex.parameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
tex.parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
tex.setImage(img);
tex.bind();
tri.bind();
LOG(img.at(256, 256).r);
stbi_image_free(raw_img_data);
LOG(prog.log()); LOG(prog.log());
GLFWwindow* window_ptr = window.getWindow(); using nb::WindowCallbacks;
while(!glfwWindowShouldClose(window_ptr)) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f); window->setCallback<nb::KEY>(
glClear(GL_COLOR_BUFFER_BIT); [](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(); tri.draw();
glfwPollEvents(); window->pollEvents();
glfwSwapBuffers(window_ptr); window->swapBuffers();
} }
return 0; return 0;