Uhhhhh big big changes

This commit is contained in:
NaifBanana 2026-08-20 08:13:26 -05:00
parent 3e7e6acc3a
commit ac671c3770
20 changed files with 561 additions and 285 deletions

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,6 +22,10 @@ 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
@ -53,29 +58,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 +105,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()

View File

@ -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)

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;
@ -72,7 +72,7 @@ class Buffer : public OpenGLObject {
Buffer(GLenum target) : Target(target) {} 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(); bind();
return _id; return _id;
@ -80,7 +80,7 @@ class Buffer : public OpenGLObject {
virtual void remove() override { virtual void remove() override {
if (_id) { if (_id) {
unbind(); unbind();
glDeleteBuffers(1, &_id); OPENGL_CALL(glDeleteBuffers(1, &_id));
_id = 0; _id = 0;
} }
} }
@ -93,15 +93,17 @@ class Buffer : public OpenGLObject {
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;

View File

@ -9,13 +9,12 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <NBGraphics/Buffers.h> #include <NBGraphics/Buffers.hpp>
#include <NBGraphics/Shader.h> #include <NBGraphics/VertexArray.hpp>
#include <NBGraphics/VAOManager.hpp>
#define THROW_DRAW_ERROR(msg) throw DrawError(msg, __FILE__, __LINE__); #define THROW_DRAW_ERROR(msg) throw DrawError(msg, __FILE__, __LINE__);
namespace NB{ namespace nb{
class DrawError : public std::runtime_error { class DrawError : public std::runtime_error {
public: public:

View File

@ -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);

View File

@ -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

View File

@ -134,40 +134,95 @@ 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) void clear() {
: width(x), height(y), _data(nullptr) {} 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];
auto& ret = Image(width, height, data_ptr);
if (data) {
std::memcpy(data_ptr, data, data_size);
}
ret._data_managed = true;
return std::move(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); }
_data = cpy._data;
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 +243,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

View File

@ -2,14 +2,40 @@
#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;
class OpenGLError : public Error<OpenGLError> {
using Base = Error<OpenGLError>;
public:
using Base::Base;
enum Codes : unsigned int {
NO_ERROR = GL_NO_ERROR,
INVALID_ENUM = GL_INVALID_ENUM,
INVALID_VALUE = GL_INVALID_VALUE,
INVALID_OPERATION = GL_INVALID_OPERATION,
INVALID_FRAMEBUFFER_OPERATION = GL_INVALID_FRAMEBUFFER_OPERATION,
OUT_OF_MEMORY = GL_OUT_OF_MEMORY,
STACK_UNDERFLOW = GL_STACK_UNDERFLOW,
STACK_OVERFLOW = GL_STACK_OVERFLOW
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
static OpenGLError status();
};
class OpenGLObjectError : public Error<OpenGLObjectError> {
using Base = Error<OpenGLObjectError>;
public: public:
using Base::Base; using Base::Base;
@ -35,7 +61,7 @@ class OpenGLObject {
GLuint id() const { return _id; } GLuint id() const { return _id; }
protected: protected:
using Codes = OGLError::Codes; using Codes = OpenGLObjectError::Codes;
OpenGLObject() = default; OpenGLObject() = default;
virtual GLuint declare() = 0; virtual GLuint declare() = 0;
@ -45,4 +71,43 @@ class OpenGLObject {
}; };
} // 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 auto no_err = nb::OpenGLError::NO_ERROR;
auto stat = nb::OpenGLError::status();
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_();
fn();
check_();
} else {
check_();
auto ret = fn();
check_();
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

View File

@ -78,8 +78,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 +88,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));
} }
} }
@ -113,7 +113,7 @@ class Program : public OpenGLObject {
operator bool(); operator bool();
~Program() { remove(); } ~Program() { remove(); }
virtual void bind() const override { virtual void bind() const override {
glUseProgram(_id); OPENGL_CALL(glUseProgram(_id));
} }
virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ } virtual void unbind() const override { /* TODO: Some warning of some kind perhaps*/ }
GLint status(GLenum) const; GLint status(GLenum) const;
@ -125,13 +125,13 @@ class Program : public OpenGLObject {
GLint _success; GLint _success;
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));
} }
} }

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,6 +16,9 @@ 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;
@ -23,11 +28,13 @@ class RenderTarget : public OpenGLObject {
: Target(rhs.Target), Base(std::move(rhs)) {} : Target(rhs.Target), Base(std::move(rhs)) {}
public: public:
using Base::Base;
using Base::id; using Base::id;
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,69 @@ 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;
virtual void bind() const override { virtual 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 { virtual 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;
@ -102,52 +121,110 @@ struct OGLPixelFormat<Pixel<T, Channels...>>;
template<> template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue>> { struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue>> {
static constexpr GLenum glFormat = GL_RGB; 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<> template<>
struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> { struct OGLPixelFormat<Pixel<uint8_t, Red, Green, Blue, Alpha>> {
static constexpr GLenum glFormat = GL_RGBA; 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<>
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<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(); }
}
};
} // namespace nb } // namespace nb
#endif // _NB_TEXTURES #endif // _NB_TEXTURES

View File

@ -88,15 +88,17 @@ class VAO : public OpenGLObject {
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; VertexAttributePointerList attributes() const;
VertexAttributePointerList attributes(const VertexAttributePointerList&); VertexAttributePointerList attributes(const VertexAttributePointerList&);
@ -114,13 +116,13 @@ class VAO : public OpenGLObject {
if(_id) { if(_id) {
disable(); disable();
bind(); bind();
glDeleteVertexArrays(1, &_id); OPENGL_CALL(glDeleteVertexArrays(1, &_id));
_id = 0; _id = 0;
} }
} }
virtual GLuint declare() override { virtual GLuint declare() override {
if (!_id) { if (!_id) {
glGenVertexArrays(1, &_id); OPENGL_CALL(glGenVertexArrays(1, &_id));
} }
bind(); bind();
return _id; return _id;

View File

@ -3,6 +3,7 @@
#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 <map>
@ -13,8 +14,8 @@
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;

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"}
}); });
@ -22,10 +22,10 @@ Buffer::Buffer(Buffer&& rval) : Target(rval.Target) {
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 +44,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 +65,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_) {

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()

View File

@ -1,23 +1,65 @@
#include <NBGraphics/OGLObjects.hpp> #include <NBGraphics/OGLObjects.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"}
}; };
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());
}
OpenGLObject::OpenGLObject(OpenGLObject&& rval) { OpenGLObject::OpenGLObject(OpenGLObject&& rval) {
*this = std::move(rval); *this = std::move(rval);
} }
OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) { OpenGLObject& OpenGLObject::operator=(OpenGLObject&& rhs) {
if (_id) { THROW(OGLError(Codes::HANGING_OBJECT)); } 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),
};
} // namespace nb } // namespace nb

View File

@ -41,14 +41,14 @@ 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;
@ -57,9 +57,9 @@ std::string Shader::log() const {
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,14 +70,14 @@ 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;

View File

@ -41,17 +41,17 @@ VertexAttributePointerList VAO::attributes(const VertexAttributePointerList& att
_attrs = attrs_; _attrs = attrs_;
bind(); bind();
for (auto attr_ptr : attrs_) { for (auto attr_ptr : attrs_) {
glBindBuffer(GL_ARRAY_BUFFER, attr_ptr.buffer); OPENGL_CALL(glBindBuffer(GL_ARRAY_BUFFER, attr_ptr.buffer));
GLuint idx = attr_ptr.index; GLuint idx = attr_ptr.index;
glVertexAttribPointer( OPENGL_CALL(glVertexAttribPointer(
idx, idx,
attr_ptr.attribute.GLSLSize, attr_ptr.attribute.GLSLSize,
attr_ptr.attribute.GLSLType, attr_ptr.attribute.GLSLType,
attr_ptr.attribute.GLSLNormalization, attr_ptr.attribute.GLSLNormalization,
attr_ptr.attribute.layout.stride, attr_ptr.attribute.layout.stride,
(void*)attr_ptr.attribute.layout.offset (void*)attr_ptr.attribute.layout.offset
); ));
glEnableVertexAttribArray(idx); OPENGL_CALL(glEnableVertexAttribArray(idx));
} }
unbind(); unbind();
return _attrs; return _attrs;
@ -70,7 +70,7 @@ void VAO::enable() const {
if (_id) { if (_id) {
bind(); bind();
for(auto attr_ptr : _attrs) { for(auto attr_ptr : _attrs) {
glEnableVertexAttribArray(attr_ptr.index); OPENGL_CALL(glEnableVertexAttribArray(attr_ptr.index));
} }
unbind(); unbind();
} }
@ -79,7 +79,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(attr(idx).index));
unbind(); unbind();
} }
} }
@ -88,7 +88,7 @@ void VAO::disable() const {
if(_id) { if(_id) {
bind(); bind();
for(auto attr_ptr : _attrs) { for(auto attr_ptr : _attrs) {
glDisableVertexAttribArray(attr_ptr.index); OPENGL_CALL(glDisableVertexAttribArray(attr_ptr.index));
} }
unbind(); unbind();
} }
@ -97,7 +97,7 @@ 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(attr(idx).index));
unbind(); unbind();
} }
} }
@ -120,7 +120,9 @@ VertexGroup& VertexGroup::operator=(VertexGroup&& rhs) {
void VertexGroup::draw() const { void VertexGroup::draw() const {
bind(); bind();
glDrawElements(primitive, _ebo->size(), _ebo->glslType(), 0); OPENGL_CALL(
glDrawElements(primitive, _ebo->size(), _ebo->glslType(), 0)
);
} }
size_t VertexGroup::addBuffer(const VertexData& vertex_data_) { size_t VertexGroup::addBuffer(const VertexData& vertex_data_) {
@ -177,7 +179,7 @@ VertexDataVec VertexGroup::dropBuffers() {
VertexData VertexGroup::dropBuffer(size_t idx) { VertexData VertexGroup::dropBuffer(size_t idx) {
if (idx >= _vertex_data.size()) { if (idx >= _vertex_data.size()) {
THROW(Error(Error<>::INDEX_ERROR)); THROW(Error(Error<>::OUT_OF_RANGE));
} }
VertexDataVec tmp; VertexDataVec tmp;
VertexData ret; VertexData ret;

View File

@ -16,13 +16,13 @@ static std::map<int, int> defailt_window_hints = {
#endif #endif
}; };
using OpenGLErrorCodes = OpenGLError::Codes; using GLFWCodes = GLFWError::Codes;
const std::string OpenGLError::type = "nb::OpenGLError"; const std::string GLFWError::type = "nb::GLFWError";
const ErrorCodeMap OpenGLError::ErrorMessages = { const ErrorCodeMap GLFWError::ErrorMessages = {
{OpenGLErrorCodes::UNDEFINED, "Error"}, {GLFWCodes::UNDEFINED, "Error"},
{OpenGLErrorCodes::INIT_FAILED, "GLFW initialization failed"}, {GLFWCodes::INIT_FAILED, "GLFW initialization failed"},
{OpenGLErrorCodes::GLFW_INTIALIZED, "GLFW has already been initialized"}, {GLFWCodes::GLFW_INTIALIZED, "GLFW has already been initialized"},
{OpenGLErrorCodes::GLAD_FAILED, "GLAD initialization failed"} {GLFWCodes::GLAD_FAILED, "GLAD initialization failed"}
}; };
using WindowErrorCodes = WindowError::Codes; using WindowErrorCodes = WindowError::Codes;
@ -44,7 +44,7 @@ int Window::getGLFWHint(int hint_key) {
int Window::setGLFWHint(int hint_key, int hint_val) { int Window::setGLFWHint(int hint_key, int hint_val) {
if (Window::_glfw_init) { if (Window::_glfw_init) {
THROW(OpenGLError(OpenGLErrorCodes::GLFW_INTIALIZED)); THROW(GLFWError(GLFWCodes::GLFW_INTIALIZED));
} else { } else {
GLFWHints[hint_key] = hint_val; GLFWHints[hint_key] = hint_val;
} }
@ -74,7 +74,7 @@ Window::Window(const uint16_t x, const uint16_t y, const char* initName, GLFWmon
Window::_glfw_init = true; Window::_glfw_init = true;
} else { } else {
if (Window::StrictInitialization) { if (Window::StrictInitialization) {
THROW(OpenGLError(OpenGLErrorCodes::INIT_FAILED)); THROW(GLFWError(GLFWCodes::INIT_FAILED));
} }
} }
} }
@ -147,12 +147,14 @@ int Window::init() {
if (!gladResponse) { if (!gladResponse) {
Window::checkKillGLFW(); Window::checkKillGLFW();
if (Window::StrictInitialization) { if (Window::StrictInitialization) {
THROW(OpenGLError(OpenGLErrorCodes::GLAD_FAILED)); THROW(GLFWError(GLFWCodes::GLAD_FAILED));
} }
} }
_init = true; _init = true;
glViewport(0, 0, windowSize[0], windowSize[1]); OPENGL_CALL(
glViewport(0, 0, windowSize[0], windowSize[1])
);
return gladResponse; return gladResponse;
} }
@ -173,7 +175,9 @@ std::string Window::getName() const {
void Window::resize(const std::array<uint16_t, 2> newSize) { void Window::resize(const std::array<uint16_t, 2> newSize) {
windowSize = newSize; windowSize = newSize;
_aspect_ratio = float(newSize[0]) / float(newSize[1]); _aspect_ratio = float(newSize[0]) / float(newSize[1]);
glViewport(0, 0, windowSize[0], windowSize[1]); OPENGL_CALL(
glViewport(0, 0, windowSize[0], windowSize[1])
);
glfwSetWindowSize(window, windowSize[0], windowSize[1]); glfwSetWindowSize(window, windowSize[0], windowSize[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)

View File

@ -2,14 +2,16 @@
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" #include "stb_image.h"
#include <NBCore/Errors.hpp>
#include <NBGraphics/Image.hpp> #include <NBGraphics/Image.hpp>
#include <NBGraphics/ProgramPipeline.hpp> #include <NBGraphics/ProgramPipeline.hpp>
#include <NBGraphics/VertexArray.hpp> #include <NBGraphics/VertexArray.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!"); nb::Window window(400, 400, "Hello!");
window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
@ -19,12 +21,12 @@ int main() {
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,71 +35,41 @@ 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::VertexGroup tri(data, {
nb::VertexAttribute{ nb::VertexAttribute{
2, 2,
GL_FLOAT, GL_FLOAT,
false, false,
{0, 16} {0, 8}
}, },
nb::VertexAttribute{
2,
GL_FLOAT,
false,
{8, 16}
}
}, indxs); }, 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(); GLFWwindow* window_ptr = window.getWindow();
while(!glfwWindowShouldClose(window_ptr)) { while(!glfwWindowShouldClose(window_ptr)) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f); OPENGL_CALL(glClearColor(0.2f, 0.3f, 0.3f, 1.0f));
glClear(GL_COLOR_BUFFER_BIT); OPENGL_CALL(glClear(GL_COLOR_BUFFER_BIT));
tri.draw(); tri.draw();
glfwPollEvents(); glfwPollEvents();
glfwSwapBuffers(window_ptr); glfwSwapBuffers(window_ptr);