Squashed 'vendor/gl/' content from commit 0235739

git-subtree-dir: vendor/gl
git-subtree-split: 02357397e4f0f82afc00a8b59c73332a4c996db1
This commit is contained in:
Gero Müller 2017-11-02 12:45:15 +10:00
commit f65df21278
14 changed files with 1949 additions and 0 deletions

15
CMakeLists.txt Normal file
View File

@ -0,0 +1,15 @@
project(gl)
set(HEADER_FILES
GlBuffers.h
GlDebug.h
GlFrameBuffer.h
GlGeometry.h
GlLighting.h
GlMethods.h
GlShaders.h
GlVertexArrays.h
)
add_library(gl STATIC ${HEADER_FILES})
set_target_properties(gl PROPERTIES LINKER_LANGUAGE CXX)

178
GlBuffers.h Normal file
View File

@ -0,0 +1,178 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#include <vector>
#include <cassert>
#include <memory>
namespace gl {
template<GLenum BufferType>
class Buffer {
GLuint buffer;
public:
Buffer() :
buffer(0) {
glGenBuffers(1, &buffer);
assert(buffer != 0);
}
Buffer(Buffer && other) :
buffer(0) {
std::swap(other.buffer, buffer);
}
template<typename T>
Buffer(const std::vector<T> & data) :
buffer(0) {
glGenBuffers(1, &buffer);
bind();
load(data.size() * sizeof(T), &data[0]);
unbind();
}
template<typename T, size_t SIZE>
Buffer(T (&array)[SIZE]) :
buffer(0) {
glGenBuffers(1, &buffer);
bind();
load(SIZE * sizeof(T), array);
unbind();
}
// template<typename T> Buffer(const std::vector<T> & data);0
// template<typename T, size_t SIZE> Buffer(const T (&array)[SIZE]);
virtual ~Buffer() {
glDeleteBuffers(1, &buffer);
}
void load(size_t size, const void * data, GLenum usage = GL_STATIC_DRAW) {
glBufferData(BufferType, size, data, usage);
}
void bind() const {
glBindBuffer(BufferType, buffer);
}
static void unbind() {
glBindBuffer(BufferType, 0);
}
};
typedef Buffer<GL_ELEMENT_ARRAY_BUFFER> IndexBuffer;
typedef std::shared_ptr<IndexBuffer> IndexBufferPtr;
typedef Buffer<GL_ARRAY_BUFFER> VertexBuffer;
typedef std::shared_ptr<VertexBuffer> VertexBufferPtr;
class BufferLoader {
public:
virtual ~BufferLoader() {
}
virtual const GLvoid* getData() const = 0;
virtual GLsizeiptr getSize() const = 0;
};
template<class T> class VectorLoader: public BufferLoader {
public:
typedef std::vector<T> V;
const V & data;
VectorLoader(const V & data) :
data(data) {
}
const GLvoid* getData() const {
const T * ptr = &(this->data[0]);
return ptr;
}
GLsizeiptr getSize() const {
return sizeof(T) * data.size();
}
};
template<typename T> VectorLoader<T> makeVectorLoader(
const std::vector<T> & vector) {
return VectorLoader<T>(vector);
}
template<typename T, size_t SIZE> class ArrayLoader: public BufferLoader {
public:
const T * data;
ArrayLoader(const T * data) :
data(data) {
}
const GLvoid* getData() const {
return (const GLvoid*)data;
}
GLsizeiptr getSize() const {
return sizeof(T) * SIZE;
}
};
template<typename T, size_t SIZE> ArrayLoader<T, SIZE> makeArrayLoader(
T * pointer) {
return ArrayLoader<T, SIZE>(pointer);
}
template<typename T, size_t SIZE> ArrayLoader<T, SIZE> makeArrayLoader(
T(&array)[SIZE]) {
return ArrayLoader<T, SIZE>(array);
}
template <GLenum BufferType>
Buffer<BufferType> & operator <<(Buffer<BufferType> & buffer, const BufferLoader & loader) {
buffer.bind();
buffer.load(loader.getSize(), loader.getData());
Buffer<BufferType>::unbind();
GL_CHECK_ERROR;
return buffer;
}
template <GLenum BufferType>
Buffer<BufferType> & operator <<(Buffer<BufferType> & buffer, BufferLoader && loader) {
GL_CHECK_ERROR;
buffer.bind();
GL_CHECK_ERROR;
buffer.load(loader.getSize(), loader.getData());
GL_CHECK_ERROR;
Buffer<BufferType>::unbind();
GL_CHECK_ERROR;
return buffer;
}
} // gl

77
GlDebug.h Normal file
View File

@ -0,0 +1,77 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#ifdef WIN32
#include <Windows.h>
#endif
#include <stdexcept>
#include <iostream>
#include <ostream>
#include <cstdarg>
#include <string>
#include <cstring>
#ifdef WIN32
#pragma warning(disable: 4996)
#define snprintf _snprintf
#endif
namespace gl {
class error : public std::runtime_error {
public:
GLenum errorCode;
error(GLenum errorCode)
: errorCode(errorCode), runtime_error("OpenGL Error") {
}
static inline void check() {
GLenum errorCode = glGetError();
if (errorCode != 0) {
throw error(errorCode);
}
}
};
class shader_error : public std::runtime_error {
public:
GLuint shader;
shader_error(GLuint shader, const std::string & log)
: shader(shader), runtime_error("OpenGL Shader Error: " + log) {
}
static inline void check() {
GLenum errorCode = glGetError();
if (errorCode != 0) {
throw error(errorCode);
}
}
};
}
#define GL_CHECK_ERROR gl::error::check()

167
GlFrameBuffer.h Normal file
View File

@ -0,0 +1,167 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#include "GlTexture.h"
#include "GlDebug.h"
namespace gl {
struct FrameBuffer {
GLuint frameBuffer;
FrameBuffer() : frameBuffer(0) {
glGenFramebuffers(1, &frameBuffer);
}
virtual ~FrameBuffer() {
if (frameBuffer) {
glDeleteFramebuffers(1, &frameBuffer);
GL_CHECK_ERROR;
}
}
void bind(GLenum target = GL_FRAMEBUFFER) {
glBindFramebuffer(target, frameBuffer);
}
static void unbind(GLenum target = GL_FRAMEBUFFER) {
glBindFramebuffer(target, 0);
}
static bool checkStatus(GLenum target = GL_FRAMEBUFFER) {
GLuint status = glCheckFramebufferStatus(target);
switch(status) {
case GL_FRAMEBUFFER_COMPLETE:
return true;
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
std::cerr << "framebuffer incomplete attachment" << std::endl;
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
std::cerr << "framebuffer missing attachment" << std::endl;
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
std::cerr << "framebuffer incomplete draw buffer" << std::endl;
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
std::cerr << "framebuffer incomplete read buffer" << std::endl;
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
std::cerr << "framebuffer incomplete multisample" << std::endl;
break;
case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS :
std::cerr << "framebuffer incomplete layer targets" << std::endl;
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
std::cerr << "framebuffer unsupported internal format or image" << std::endl;
break;
default:
std::cerr << "other framebuffer error" << std::endl;
break;
}
return false;
}
template <GLenum TextureType, GLenum TextureFormat>
void attach(int attachPoint, std::shared_ptr<Texture<TextureType, TextureFormat> > & texture) {
glFramebufferTexture2D(GL_FRAMEBUFFER, attachPoint, TextureType, *texture, 0);
}
};
typedef std::shared_ptr<FrameBuffer> FrameBufferPtr;
template <GLenum ColorFormat = GL_RGBA8>
struct TFrameBufferWrapper {
typedef Texture<GL_TEXTURE_2D, ColorFormat> ColorTexture;
FrameBufferPtr frameBuffer;
typename ColorTexture::Ptr color;
Texture2dDepth::Ptr depth;
glm::ivec2 size;
void init(const glm::ivec2 & size) {
this->size = size;
GL_CHECK_ERROR;
if (!frameBuffer) {
frameBuffer = FrameBufferPtr(new FrameBuffer());
}
frameBuffer->bind();
GL_CHECK_ERROR;
if (!color) {
color = typename ColorTexture::Ptr(new ColorTexture());
color->bind();
color->parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);
color->parameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
color->parameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
color->parameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
color->storage2d(size);
Texture2d::unbind();
}
frameBuffer->attach(GL_COLOR_ATTACHMENT0, color);
GL_CHECK_ERROR;
if (!depth) {
depth = Texture2dDepth::Ptr(new Texture2dDepth());
depth->bind();
depth->storage2d(size);
Texture2dDepth::unbind();
}
frameBuffer->attach(GL_DEPTH_ATTACHMENT, depth);
GL_CHECK_ERROR;
if (!frameBuffer->checkStatus()) {
throw std::runtime_error("Bad framebuffer creation");
}
GL_CHECK_ERROR;
FrameBuffer::unbind();
GL_CHECK_ERROR;
}
void activate() {
frameBuffer->bind();
viewport(size);
}
static void deactivate() {
FrameBuffer::unbind();
}
};
typedef TFrameBufferWrapper<> FrameBufferWrapper;
} // gl

167
GlGeometry.h Normal file
View File

@ -0,0 +1,167 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#include "GlBuffers.h"
#include "GlVertexArrays.h"
namespace gl {
class Geometry;
typedef std::shared_ptr<Geometry> GeometryPtr;
class Geometry {
public:
static const int VERTEX_ATTRIBUTE_SIZE = 4;
static const int BYTES_PER_ATTRIBUTE = (sizeof(float)
* VERTEX_ATTRIBUTE_SIZE);
enum Flag {
HAS_NORMAL = 0x01,
HAS_COLOR = 0x02,
HAS_TEXTURE = 0x04,
};
VertexBufferPtr vertices;
IndexBufferPtr indices;
VertexArrayPtr vertexArray;
unsigned int elements;
GLenum elementType;
unsigned int verticesPerElement;
unsigned int flags;
void bindVertexArray() {
vertexArray->bind();
}
static void unbindVertexArray() {
gl::VertexArray::unbind();
}
static unsigned int getStride(unsigned int flags) {
int result = VERTEX_ATTRIBUTE_SIZE;
if (flags & Geometry::Flag::HAS_NORMAL) {
result += VERTEX_ATTRIBUTE_SIZE;
}
if (flags & Geometry::Flag::HAS_COLOR) {
result += VERTEX_ATTRIBUTE_SIZE;
}
if (flags & Geometry::Flag::HAS_TEXTURE) {
result += VERTEX_ATTRIBUTE_SIZE;
}
return result * sizeof(float);
}
unsigned int getStride() {
return getStride(flags);
}
void draw() {
glDrawElements(elementType, elements * verticesPerElement,
GL_UNSIGNED_INT, (void*) 0);
}
Geometry(
const std::vector<glm::vec4> & in_vertices,
const std::vector<GLuint> & in_indices,
unsigned int elements = 0,
unsigned int flags = 0,
GLenum elementType = GL_TRIANGLES,
unsigned int verticesPerElement = 3)
: elements(elements),
elementType(elementType),
flags(flags),
vertexArray(new gl::VertexArray()),
verticesPerElement(verticesPerElement) {
vertices = VertexBufferPtr(new VertexBuffer());
*vertices << VectorLoader<glm::vec4>(in_vertices);
indices = IndexBufferPtr(new IndexBuffer());
*indices << VectorLoader<GLuint>(in_indices);
buildVertexArray();
}
Geometry(
const gl::VertexBufferPtr in_vertices,
const gl::IndexBufferPtr in_indices,
unsigned int elements = 0,
unsigned int flags = 0,
GLenum elementType = GL_TRIANGLES,
unsigned int verticesPerElement = 3)
: vertices(in_vertices),
indices(in_indices),
elements(elements),
flags(flags),
vertexArray(new gl::VertexArray()),
elementType(elementType),
verticesPerElement(verticesPerElement) {
buildVertexArray();
}
void buildVertexArray() {
vertexArray->bind();
{
indices->bind();
vertices->bind();
GL_CHECK_ERROR;
unsigned int stride = getStride(flags);
GLfloat * offset = 0;
glEnableVertexAttribArray(gl::Attribute::Position);
glVertexAttribPointer(gl::Attribute::Position, 3, GL_FLOAT, GL_FALSE,
stride, offset);
GL_CHECK_ERROR;
if (flags & HAS_NORMAL) {
offset += VERTEX_ATTRIBUTE_SIZE;
glEnableVertexAttribArray(gl::Attribute::Normal);
glVertexAttribPointer(gl::Attribute::Normal, 3, GL_FLOAT, GL_FALSE,
stride, offset);
GL_CHECK_ERROR;
}
if (flags & HAS_COLOR) {
offset += VERTEX_ATTRIBUTE_SIZE;
glEnableVertexAttribArray(gl::Attribute::Color);
glVertexAttribPointer(gl::Attribute::Color, 3, GL_FLOAT, GL_FALSE,
stride, offset);
GL_CHECK_ERROR;
}
if (flags & HAS_TEXTURE) {
offset += VERTEX_ATTRIBUTE_SIZE;
glEnableVertexAttribArray(gl::Attribute::TexCoord0);
glVertexAttribPointer(gl::Attribute::TexCoord0, 2, GL_FLOAT,
GL_FALSE, stride, offset);
GL_CHECK_ERROR;
}
}
VertexArray::unbind();
IndexBuffer::unbind();
VertexBuffer::unbind();
GL_CHECK_ERROR;
}
};
} // gl

83
GlLighting.h Normal file
View File

@ -0,0 +1,83 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#include "GlShaders.h"
#include <glm/glm.hpp>
#include <vector>
namespace gl {
struct Light {
glm::vec4 position;
glm::vec4 color;
Light(const glm::vec4 & position = glm::vec4(1), const glm::vec4 & color =
glm::vec4(1)) {
this->position = position;
this->color = color;
}
};
class Lights {
std::vector<glm::vec4> lightPositions;
std::vector<glm::vec4> lightColors;
glm::vec4 ambient;
public:
// Singleton class
Lights()
: ambient(glm::vec4(0.2, 0.2, 0.2, 1.0)) {
addLight();
}
void apply(Program & renderProgram) {
renderProgram.setUniform("Ambient", ambient);
renderProgram.setUniform("LightCount", (GLint)lightPositions.size());
if (!lightPositions.empty()) {
renderProgram.setUniform4fv("LightPosition[0]", lightPositions);
renderProgram.setUniform4fv("LightColor[0]", lightColors);
}
}
void apply(ProgramPtr & program) {
apply(*program);
}
void addLight(const glm::vec4 & position = glm::vec4(1),
const glm::vec4 & color = glm::vec4(1)) {
lightPositions.push_back(position);
lightColors.push_back(color);
}
void addLight(const Light & light) {
addLight(light.position, light.color);
}
void setAmbient(const glm::vec4 & ambient) {
this->ambient = ambient;
}
};
} // gl

306
GlMethods.h Normal file
View File

@ -0,0 +1,306 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#include <vector>
namespace gl {
namespace Error {
enum {
NONE = GL_NO_ERROR,
INVALID_ENUM = GL_INVALID_ENUM,
INVALID_VALUE = GL_INVALID_VALUE,
INVALID_OPERATION = GL_INVALID_OPERATION,
// STACK_OVERFLOW = GL_STACK_OVERFLOW,
// STACK_UNDERFLOW = GL_STACK_UNDERFLOW,
OUT_OF_MEMORY = GL_OUT_OF_MEMORY,
};
}
namespace DrawMode {
enum {
POINTS = GL_POINTS,
LINE_STRIP = GL_LINE_STRIP,
LINE_LOOP = GL_LINE_LOOP,
LINES = GL_LINES,
LINE_STRIP_ADJACENCY = GL_LINE_STRIP_ADJACENCY,
LINES_ADJACENCY = GL_LINES_ADJACENCY,
TRIANGLE_STRIP = GL_TRIANGLE_STRIP,
TRIANGLE_FAN = GL_TRIANGLE_FAN,
TRIANGLES = GL_TRIANGLES,
TRIANGLE_STRIP_ADJACENCY = GL_TRIANGLE_STRIP_ADJACENCY,
TRIANGLES_ADJACENCY = GL_TRIANGLES_ADJACENCY,
PATCHES = GL_PATCHES,
};
}
inline void uniform(GLint location, GLfloat a) {
glUniform1f(location, a);
}
inline void uniform(GLint location, GLint a) {
glUniform1i(location, a);
}
inline void uniform(GLint location, const glm::vec2 & a) {
glUniform2f(location, a.x, a.y);
}
inline void uniform(GLint location, const glm::vec4 & a) {
glUniform4f(location, a.x, a.y, a.z, a.w);
}
inline void uniform(GLint location, const std::vector<glm::vec4> & a) {
glUniform4fv(location, (GLsizei) a.size(), &(a[0][0]));
}
inline void uniform(GLint location, const glm::vec3 & a) {
glUniform3f(location, a.x, a.y, a.z);
}
inline void uniform(GLint location, const glm::mat4 & a) {
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(a));
}
inline void lineWidth(GLfloat width) {
glLineWidth(width);
}
inline void clearColor(const glm::vec4 & c) {
glClearColor(c.r, c.g, c.b, c.a);
}
inline void clearColor(const glm::vec3 & c) {
glClearColor(c.r, c.g, c.b, 1.0);
}
inline void scissor(const glm::ivec2 & v, const glm::ivec2 & size) {
glScissor(v.x, v.y, size.x, size.y);
}
inline void viewport( const glm::ivec2 & pos, const glm::ivec2 & size ) {
glViewport(pos.x, pos.y, size.x, size.y);
}
inline void viewport( const glm::ivec2 & size ) {
viewport(glm::ivec2(), size);
}
}
namespace glm {
template <typename T>
inline float aspect(T const & size) {
return (float) size.x / (float)size.y;
}
}
// inline void ColorMask( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha );
// inline void AlphaFunc( GLenum func, GLclampf ref );
// inline void BlendFunc( GLenum sfactor, GLenum dfactor );
// inline void LogicOp( GLenum opcode );
// inline void CullFace( GLenum mode );
// inline void FrontFace( GLenum mode );
// inline void PointSize( GLfloat size );
// inline void LineStipple( GLint factor, GLushort pattern );
// inline void PolygonMode( GLenum face, GLenum mode );
// inline void PolygonOffset( GLfloat factor, GLfloat units );
// inline void PolygonStipple( const GLubyte *mask );
// inline void GetPolygonStipple( GLubyte *mask );
// inline void EdgeFlag( GLboolean flag );
// inline void EdgeFlagv( const GLboolean *flag );
// inline void ClipPlane( GLenum plane, const GLdouble *equation );
// inline void GetClipPlane( GLenum plane, GLdouble *equation );
// inline void DrawBuffer( GLenum mode );
// inline void ReadBuffer( GLenum mode );
// inline void Enable( GLenum cap );
// inline void Disable( GLenum cap );
// inline bool IsEnabled( GLenum cap );
// inline void EnableClientState( GLenum cap ); /* 1.1 */
// inline void DisableClientState( GLenum cap ); /* 1.1 */
// inline void GetBooleanv( GLenum pname, GLboolean *params );
// inline void GetDoublev( GLenum pname, GLdouble *params );
// inline void GetFloatv( GLenum pname, GLfloat *params );
// inline void GetIntegerv( GLenum pname, GLint *params );
// inline void PushAttrib( GLbitfield mask );
// inline void PopAttrib( void );
// inline void PushClientAttrib( GLbitfield mask ); /* 1.1 */
// inline void PopClientAttrib( void ); /* 1.1 */
// inline int32_tRenderMode( GLenum mode );
// GLAPI GLenum GLAPIENTRY glGetError( void );
// GLAPI const GLubyte * GLAPIENTRY glGetString( GLenum name );
// inline void Finish( void );
// inline void Flush( void );
// inline void Hint( GLenum target, GLenum mode );
// inline void ClearDepth( GLclampd depth );
// inline void DepthFunc( GLenum func );
// inline void DepthMask( GLboolean flag );
// inline void DepthRange( GLclampd near_val, GLclampd far_val );
// inline void ClearAccum( const glm::vec4 & color );
// inline void VertexPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr );
// inline void NormalPointer( GLenum type, GLsizei stride, const GLvoid *ptr );
// inline void ColorPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr );
// inline void IndexPointer( GLenum type, GLsizei stride, const GLvoid *ptr );
// inline void TexCoordPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr );
// inline void EdgeFlagPointer( GLsizei stride, const GLvoid *ptr );
// inline void GetPointerv( GLenum pname, GLvoid **params );
// inline void ArrayElement( GLint i );
// inline void DrawArrays( GLenum mode, GLint first, GLsizei count );
// inline void DrawElements( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices );
// inline void InterleavedArrays( GLenum format, GLsizei stride, const GLvoid *pointer );
// inline void ShadeModel( GLenum mode );
// inline void PixelZoom( GLfloat xfactor, GLfloat yfactor );
// inline void PixelStoref( GLenum pname, GLfloat param );
// inline void PixelStorei( GLenum pname, GLint param );
// inline void PixelTransferf( GLenum pname, GLfloat param );
// inline void PixelTransferi( GLenum pname, GLint param );
// inline void PixelMapfv( GLenum map, GLsizei mapsize, const GLfloat *values );
// inline void PixelMapuiv( GLenum map, GLsizei mapsize, const GLuint *values );
// inline void PixelMapusv( GLenum map, GLsizei mapsize, const GLushort *values );
// inline void GetPixelMapfv( GLenum map, GLfloat *values );
// inline void GetPixelMapuiv( GLenum map, GLuint *values );
// inline void GetPixelMapusv( GLenum map, GLushort *values );
// inline void Bitmap( const glm::ivec2 & size, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap );
// inline void ReadPixels( const glm::ivec2 & v, const glm::ivec2 & size, GLenum format, GLenum type, GLvoid *pixels );
// inline void DrawPixels( const glm::ivec2 & size, GLenum format, GLenum type, const GLvoid *pixels );
// inline void CopyPixels( const glm::ivec2 & v, const glm::ivec2 & size, GLenum type );
// inline void StencilFunc( GLenum func, GLint ref, GLuint mask );
// inline void StencilMask( GLuint mask );
// inline void StencilOp( GLenum fail, GLenum zfail, GLenum zpass );
// inline void ClearStencil( GLint s );
// inline void TexGend( GLenum coord, GLenum pname, GLdouble param );
// inline void TexGenf( GLenum coord, GLenum pname, GLfloat param );
// inline void TexGeni( GLenum coord, GLenum pname, GLint param );
// inline void TexGendv( GLenum coord, GLenum pname, const GLdouble *params );
// inline void TexGenfv( GLenum coord, GLenum pname, const GLfloat *params );
// inline void TexGeniv( GLenum coord, GLenum pname, const GLint *params );
// inline void GetTexGendv( GLenum coord, GLenum pname, GLdouble *params );
// inline void GetTexGenfv( GLenum coord, GLenum pname, GLfloat *params );
// inline void GetTexGeniv( GLenum coord, GLenum pname, GLint *params );
// inline void TexEnvf( GLenum target, GLenum pname, GLfloat param );
// inline void TexEnvi( GLenum target, GLenum pname, GLint param );
// inline void TexEnvfv( GLenum target, GLenum pname, const GLfloat *params );
// inline void TexEnviv( GLenum target, GLenum pname, const GLint *params );
// inline void GetTexEnvfv( GLenum target, GLenum pname, GLfloat *params );
// inline void GetTexEnviv( GLenum target, GLenum pname, GLint *params );
// inline void TexParameterf( GLenum target, GLenum pname, GLfloat param );
// inline void TexParameteri( GLenum target, GLenum pname, GLint param );
// inline void TexParameterfv( GLenum target, GLenum pname, const GLfloat *params );
// inline void TexParameteriv( GLenum target, GLenum pname, const GLint *params );
// inline void GetTexParameterfv( GLenum target, GLenum pname, GLfloat *params);
// inline void GetTexParameteriv( GLenum target, GLenum pname, GLint *params );
// inline void GetTexLevelParameterfv( GLenum target, GLint level, GLenum pname, GLfloat *params );
// inline void GetTexLevelParameteriv( GLenum target, GLint level, GLenum pname, GLint *params );
// inline void TexImage1D( GLenum target, GLint level, GLint internalFormat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels );
// inline void TexImage2D( GLenum target, GLint level, GLint internalFormat, const glm::ivec2 & size, GLint border, GLenum format, GLenum type, const GLvoid *pixels );
// inline void GetTexImage( GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels );
// inline void GenTextures( GLsizei n, GLuint *textures );
// inline void DeleteTextures( GLsizei n, const GLuint *textures);
// inline void BindTexture( GLenum target, GLuint texture );
// inline void PrioritizeTextures( GLsizei n, const GLuint *textures, const GLclampf *priorities );
// inline bool AreTexturesResident( GLsizei n, const GLuint *textures, GLboolean *residences );
// inline bool IsTexture( GLuint texture );
// inline void TexSubImage1D( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels );
// inline void TexSubImage2D( GLenum target, GLint level, const glm::ivec2 & offset, const glm::ivec2 & size, GLenum format, GLenum type, const GLvoid *pixels );
// inline void CopyTexImage1D( GLenum target, GLint level, GLenum internalformat, const glm::ivec2 & v, GLsizei width, GLint border );
// inline void CopyTexImage2D( GLenum target, GLint level, GLenum internalformat, const glm::ivec2 & v, const glm::ivec2 & size, GLint border );
// inline void CopyTexSubImage1D( GLenum target, GLint level, GLint xoffset, const glm::ivec2 & v, GLsizei width );
// inline void CopyTexSubImage2D( GLenum target, GLint level, const glm::ivec2 & offset, const glm::ivec2 & v, const glm::ivec2 & size );
// inline void Map1d( GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points );
// inline void Map1f( GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points );
// inline void Map2d( GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points );
// inline void Map2f( GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points );
// inline void GetMapdv( GLenum target, GLenum query, GLdouble *v );
// inline void GetMapfv( GLenum target, GLenum query, GLfloat *v );
// inline void GetMapiv( GLenum target, GLenum query, GLint *v );
// inline void EvalCoord1d( GLdouble u );
// inline void EvalCoord1f( GLfloat u );
// inline void EvalCoord2d( GLdouble u, GLdouble v );
// inline void EvalCoord2f( GLfloat u, GLfloat v );
// inline void MapGrid1d( GLint un, GLdouble u1, GLdouble u2 );
// inline void MapGrid1f( GLint un, GLfloat u1, GLfloat u2 );
// inline void MapGrid2d( GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2 );
// inline void MapGrid2f( GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2 );
// inline void EvalPoint1( GLint i );
// inline void EvalPoint2( GLint i, GLint j );
// inline void EvalMesh1( GLenum mode, GLint i1, GLint i2 );
// inline void EvalMesh2( GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2 );
// inline void Fogf( GLenum pname, GLfloat param );
// inline void Fogi( GLenum pname, GLint param );
// inline void Fogfv( GLenum pname, const GLfloat *params );
// inline void Fogiv( GLenum pname, const GLint *params );
// inline void FeedbackBuffer( GLsizei size, GLenum type, GLfloat *buffer );
// inline void PassThrough( GLfloat token );
// inline void SelectBuffer( GLsizei size, GLuint *buffer );
// inline void InitNames( void );
// inline void LoadName( GLuint name );
// inline void PushName( GLuint name );
// inline void PopName( void );
// inline void DrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices );
// inline void TexImage3D( GLenum target, GLint level, GLint internalFormat, const glm::ivec3 & size, GLint border, GLenum format, GLenum type, const GLvoid *pixels );
// inline void TexSubImage3D( GLenum target, GLint level, const glm::ivec3 & offset, const glm::ivec3 & size, GLenum format, GLenum type, const GLvoid *pixels);
// inline void CopyTexSubImage3D( GLenum target, GLint level, const glm::ivec3 & offset, GLint x, GLint y, const glm::ivec2 & size );
// inline void ColorTable( GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table );
// inline void ColorSubTable( GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data );
// inline void ColorTableParameteriv(GLenum target, GLenum pname, const GLint *params);
// inline void ColorTableParameterfv(GLenum target, GLenum pname, const GLfloat *params);
// inline void CopyColorSubTable( GLenum target, GLsizei start, const glm::ivec2 & v, GLsizei width );
// inline void CopyColorTable( GLenum target, GLenum internalformat, const glm::ivec2 & v, GLsizei width );
// inline void GetColorTable( GLenum target, GLenum format, GLenum type, GLvoid *table );
// inline void GetColorTableParameterfv( GLenum target, GLenum pname, GLfloat *params );
// inline void GetColorTableParameteriv( GLenum target, GLenum pname, GLint *params );
// inline void BlendEquation( GLenum mode );
// inline void BlendColor( const glm::vec4 & c );
// inline void Histogram( GLenum target, GLsizei width, GLenum internalformat, GLboolean sink );
// inline void ResetHistogram( GLenum target );
// inline void GetHistogram( GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values );
// inline void GetHistogramParameterfv( GLenum target, GLenum pname, GLfloat *params );
// inline void GetHistogramParameteriv( GLenum target, GLenum pname, GLint *params );
// inline void Minmax( GLenum target, GLenum internalformat, GLboolean sink );
// inline void ResetMinmax( GLenum target );
// inline void GetMinmax( GLenum target, GLboolean reset, GLenum format, GLenum types, GLvoid *values );
// inline void GetMinmaxParameterfv( GLenum target, GLenum pname, GLfloat *params );
// inline void GetMinmaxParameteriv( GLenum target, GLenum pname, GLint *params );
// inline void ConvolutionFilter1D( GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image );
// inline void ConvolutionFilter2D( GLenum target, GLenum internalformat, const glm::ivec2 & size, GLenum format, GLenum type, const GLvoid *image );
// inline void ConvolutionParameterf( GLenum target, GLenum pname, GLfloat params );
// inline void ConvolutionParameterfv( GLenum target, GLenum pname, const GLfloat *params );
// inline void ConvolutionParameteri( GLenum target, GLenum pname, GLint params );
// inline void ConvolutionParameteriv( GLenum target, GLenum pname, const GLint *params );
// inline void CopyConvolutionFilter1D( GLenum target, GLenum internalformat, const glm::ivec2 & v, GLsizei width );
// inline void CopyConvolutionFilter2D( GLenum target, GLenum internalformat, const glm::ivec2 & v, const glm::ivec2 & size);
// inline void GetConvolutionFilter( GLenum target, GLenum format, GLenum type, GLvoid *image );
// inline void GetConvolutionParameterfv( GLenum target, GLenum pname, GLfloat *params );
// inline void GetConvolutionParameteriv( GLenum target, GLenum pname, GLint *params );
// inline void SeparableFilter2D( GLenum target, GLenum internalformat, const glm::ivec2 & size, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column );
// inline void GetSeparableFilter( GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span );
// inline void ActiveTexture( GLenum texture );
// inline void ClientActiveTexture( GLenum texture );
// inline void CompressedTexImage1D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data );
// inline void CompressedTexImage2D( GLenum target, GLint level, GLenum internalformat, const glm::ivec2 & size, GLint border, GLsizei imageSize, const GLvoid *data );
// inline void CompressedTexImage3D( GLenum target, GLint level, GLenum internalformat, const glm::ivec3 & size, GLint border, GLsizei imageSize, const GLvoid *data );
// inline void CompressedTexSubImage1D( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data );
// inline void CompressedTexSubImage2D( GLenum target, GLint level, const glm::ivec2 & offset, const glm::ivec2 & size, GLenum format, GLsizei imageSize, const GLvoid *data );
// inline void CompressedTexSubImage3D( GLenum target, GLint level, const glm::ivec3 & offset, const glm::ivec3 & size, GLenum format, GLsizei imageSize, const GLvoid *data );
// inline void GetCompressedTexImage( GLenum target, GLint lod, GLvoid *img );
// inline void LoadTransposeMatrixd( const GLdouble m[16] );
// inline void LoadTransposeMatrixf( const GLfloat m[16] );
// inline void MultTransposeMatrixd( const GLdouble m[16] );
// inline void MultTransposeMatrixf( const GLfloat m[16] );
// inline void SampleCoverage( GLclampf value, GLboolean invert );

73
GlQuery.h Normal file
View File

@ -0,0 +1,73 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
namespace gl {
template <
typename GenFunction,
typename DelFunction,
typename BindFunction>
class Object {
GLuint id;
const GenFunction gen;
const DelFunction del;
const BindFunction bind;
public:
Object(GenFunction g, DelFunction del, BindFunction bind) : gen(g), del(del), bind(bind) {
}
};
template <GLenum QueryType = GL_TIME_ELAPSED> class Query {
GLuint query;
public:
Query() {
glGenQueries(1, &query);
}
virtual ~Query() {
glDeleteQueries(1, &query);
query = 0;
}
void begin() {
glBeginQuery(QueryType, query);
}
static void end() {
glEndQuery(QueryType);
}
bool available() {
GLint result;
glGetQueryObjectiv(query, GL_QUERY_RESULT_AVAILABLE, &result);
return result == GL_TRUE;
}
GLint getReult() {
GLint result = -1;
glGetQueryObjectiv(query, GL_QUERY_RESULT, &result);
return result;
}
};
typedef Query<GL_TIME_ELAPSED> TimeQuery;
typedef std::shared_ptr<gl::TimeQuery> TimeQueryPtr;
}

329
GlShaders.h Normal file
View File

@ -0,0 +1,329 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <string>
#include <map>
#include <algorithm>
#include <stdexcept>
#include <set>
#include <memory>
namespace gl {
struct Var {
std::string name;
GLint size;
GLenum type;
GLuint id;
GLint location;
// for map usage
Var()
: location(0), type(0), size(0), id(0) {
}
Var(bool uniform, GLuint program, GLuint id) {
this->id = id;
static GLchar MY_BUFFER[8192];
GLsizei bufSize = 8192;
if (uniform) {
glGetActiveUniform(program, id, bufSize, &bufSize, &size, &type,
MY_BUFFER);
} else {
glGetActiveAttrib(program, id, bufSize, &bufSize, &size, &type,
MY_BUFFER);
}
name = std::string(MY_BUFFER, bufSize);
if (uniform) {
location = glGetUniformLocation(program, name.c_str());
} else {
location = glGetAttribLocation(program, name.c_str());
}
}
};
class Shader {
friend class Program;
GLenum type;
GLuint shader;
std::string source;
public:
Shader(GLenum type, const std::string & source)
: type(type), shader(0), source(source) {
// Create the shader object
GLuint newShader = glCreateShader(type);
if (newShader == 0) {
throw std::runtime_error("Unable to create shader object");
}
{
static const char * c_str;
// std::string shaderSrc = Files::read(fileName);
// Load the shader source
glShaderSource(newShader, 1, &(c_str = source.c_str()), NULL);
}
// Compile the shader
glCompileShader(newShader);
// Check the compile status
GLint compiled;
glGetShaderiv(newShader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
std::string log = getLog(newShader);
throw shader_error(shader, log);
}
if (0 != shader) {
glDeleteShader(shader);
}
shader = newShader;
}
virtual ~Shader() {
glDeleteShader(shader);
}
static std::string getLog(GLuint shader) {
std::string log;
GLint infoLen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen > 1) {
char* infoLog = new char[infoLen];
glGetShaderInfoLog(shader, infoLen, NULL, infoLog);
log = std::string(infoLog);
delete[] infoLog;
}
return log;
}
};
typedef std::shared_ptr<Shader> ShaderPtr;
namespace Attribute {
enum {
Position = 0,
TexCoord0 = 1,
Normal = 2,
Color = 3,
TexCoord1 = 4,
};
}
class Program {
typedef std::map<std::string, Var> Map;
typedef std::set<std::string> Set;
ShaderPtr vs;
ShaderPtr fs;
GLuint program;
Map uniforms;
Map attributes;
Set configuredUniforms;
public:
GLint getUniformLocation(const std::string & name) const {
return uniforms.count(name) ? uniforms.at(name).location : -1;
}
GLint getAttributeLocation(const std::string & name) const {
return attributes.count(name) ? attributes.at(name).location : -1;
}
public:
static std::string getLog(GLuint program) {
std::string log;
GLint infoLen = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen > 1) {
char* infoLog = new char[infoLen];
glGetProgramInfoLog(program, infoLen, NULL, infoLog);
log = std::string(infoLog);
delete[] infoLog;
}
return log;
}
public:
Program(const ShaderPtr & vs, const ShaderPtr & fs)
: vs(vs), fs(fs), program(0) {
if (0 != program) {
glDeleteProgram(program);
program = 0;
}
// Create the program object
program = glCreateProgram();
if (program == 0)
throw std::runtime_error("Failed to allocate gl program");
glAttachShader(program, vs->shader);
glAttachShader(program, fs->shader);
// Bind vPosition to attribute 0
glBindAttribLocation(program, 0, "vPosition");
// Link the newProgram
glLinkProgram(program);
// Check the link status
GLint linked;
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked) {
std::string log = getLog(program);
throw std::runtime_error(log);
}
int numVars;
glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES, &numVars);
for (int i = 0; i < numVars; ++i) {
Var var(false, program, i);
// SAY("Found attribute %s at location %d", var.name.c_str(), var.location);
attributes[var.name] = var;
}
glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &numVars);
for (int i = 0; i < numVars; ++i) {
Var var(true, program, i);
//SAY("Found uniform %s at location %d", var.name.c_str(), var.location);
uniforms[var.name] = var;
}
}
virtual ~Program() {
glDeleteProgram(program);
}
void setUniform(const std::string & name, GLfloat a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniform1f(location, a);
}
void setUniform(const std::string & name, GLint a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniform1i(location, a);
}
void setUniform(const std::string & name, bool a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniform1i(location, a ? 1 : 0);
}
void setUniform(const std::string & name, const glm::vec2 & a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniform2f(location, a.x, a.y);
}
void setUniform(const std::string & name, const glm::vec3 & a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniform3f(location, a.x, a.y, a.z);
}
void setUniform(const std::string & name, const glm::vec4 & a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniform4f(location, a.x, a.y, a.z, a.w);
}
void setUniform(const std::string & name, const std::vector<glm::vec4> & a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniform4fv(location, (GLsizei) a.size(), &(a[0][0]));
}
void setUniform(const std::string & name, const glm::mat4 & a) {
configuredUniforms.insert(name);
GLint location = getUniformLocation(name);
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(a));
}
inline void setUniform1f(const std::string & name, GLfloat a) {
setUniform(name, a);
}
inline void setUniform1i(const std::string & name, GLint a) {
setUniform(name, a);
}
inline void setUniform2f(const std::string & name, const glm::vec2 & a) {
setUniform(name, a);
}
inline void setUniform4f(const std::string & name, const glm::vec4 & a) {
setUniform(name, a);
}
inline void setUniform3f(const std::string & name, const glm::vec3 & a) {
setUniform(name, a);
}
inline void setUniform4fv(const std::string & name, const std::vector<glm::vec4> & a) {
setUniform(name, a);
}
inline void setUniform4x4f(const std::string & name, const glm::mat4 & a) {
setUniform(name, a);
}
void checkConfigured() {
Set existingUniforms;
// Option #2
std::for_each(std::begin(uniforms), std::end(uniforms),
[&] (Map::const_reference element)
{
existingUniforms.insert(element.first);
});
std::for_each(std::begin(configuredUniforms),
std::end(configuredUniforms), [&] (Set::const_reference element)
{
existingUniforms.erase(element);
});
// assert(existingUniforms.size() == 0);
}
void use() {
glUseProgram(program);
}
static void clear() {
glUseProgram(0);
}
};
typedef std::shared_ptr<Program> ProgramPtr;
} // gl

154
GlStacks.h Normal file
View File

@ -0,0 +1,154 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#include <stack>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "GlShaders.h"
#include "GlLighting.h"
namespace gl {
class MatrixStack : public std::stack<glm::mat4> {
const std::string uniformName;
public:
MatrixStack(const std::string & uniformName)
: uniformName(uniformName) {
push(glm::mat4());
}
MatrixStack & apply(Program & program) {
program.setUniform4x4f(uniformName, top());
return *this;
}
MatrixStack & apply(ProgramPtr & program) {
apply(*program);
return *this;
}
MatrixStack & pop() {
std::stack<glm::mat4>::pop();
assert(!empty());
return *this;
}
MatrixStack & push() {
emplace(top());
return *this;
}
MatrixStack & identity() {
top() = glm::mat4();
return *this;
}
MatrixStack & push(const glm::mat4 & mat) {
std::stack<glm::mat4>::push(mat);
return *this;
}
MatrixStack & rotate(const glm::mat3 & rotation) {
return postMultiply(glm::mat4(rotation));
}
MatrixStack & rotate(const glm::quat & rotation) {
return postMultiply(glm::mat4_cast(rotation));
}
MatrixStack & rotate(float theta, const glm::vec3 & axis) {
return postMultiply(glm::rotate(glm::mat4(), theta, axis));
}
MatrixStack & translate(float translation) {
return translate(glm::vec3(translation, 0, 0));
}
MatrixStack & translate(const glm::vec2 & translation) {
return translate(glm::vec3(translation, 0));
}
MatrixStack & translate(const glm::vec3 & translation) {
return postMultiply(glm::translate(glm::mat4(), translation));
}
MatrixStack & scale(float factor) {
return scale(glm::vec3(factor));
}
MatrixStack & scale(const glm::vec3 & scale) {
return postMultiply(glm::scale(glm::mat4(), scale));
}
MatrixStack & transform(const glm::mat4 & xfm) {
return postMultiply(xfm);
}
MatrixStack & preMultiply(const glm::mat4 & xfm) {
top() = xfm * top();
return *this;
}
MatrixStack & postMultiply(const glm::mat4 & xfm) {
top() *= xfm;
return *this;
}
// Remove the rotation component of a matrix. useful for billboarding
MatrixStack & unrotate() {
glm::quat inverse = glm::inverse(glm::quat_cast(top()));
top() = top() * glm::mat4_cast(inverse);
return *this;
}
// Remove the translation component of a matrix. useful for skyboxing
MatrixStack & untranslate() {
top()[3] = glm::vec4(0, 0, 0, 1);
return *this;
}
};
class Stacks {
public:
static MatrixStack & projection() {
static MatrixStack projection("Projection");
return projection;
}
static MatrixStack & modelview() {
static MatrixStack modelview("ModelView");
return modelview;
}
static Lights & lights() {
static Lights lights;
return lights;
}
};
} // gl

123
GlTexture.h Normal file
View File

@ -0,0 +1,123 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
#include <glm/glm.hpp>
#include <memory>
namespace gl {
namespace TextureTarget2D {
enum Enum {
TEXTURE_2D = GL_TEXTURE_2D,
PROXY_TEXTURE_2D = GL_PROXY_TEXTURE_2D,
TEXTURE_1D_ARRAY = GL_TEXTURE_1D_ARRAY,
PROXY_TEXTURE_1D_ARRAY = GL_PROXY_TEXTURE_1D_ARRAY,
TEXTURE_RECTANGLE = GL_TEXTURE_RECTANGLE,
PROXY_TEXTURE_RECTANGLE = GL_PROXY_TEXTURE_RECTANGLE,
TEXTURE_CUBE_MAP_POSITIVE_X = GL_TEXTURE_CUBE_MAP_POSITIVE_X,
TEXTURE_CUBE_MAP_NEGATIVE_X = GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
TEXTURE_CUBE_MAP_POSITIVE_Y = GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
TEXTURE_CUBE_MAP_NEGATIVE_Y = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
TEXTURE_CUBE_MAP_POSITIVE_Z = GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
TEXTURE_CUBE_MAP_NEGATIVE_Z = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
PROXY_TEXTURE_CUBE_MAP = GL_PROXY_TEXTURE_CUBE_MAP
};
}
template <
GLenum TextureType = GL_TEXTURE_2D,
GLenum TextureFormat = GL_RGBA8
>
class Texture {
public:
GLuint texture;
Texture()
: texture(0) {
glGenTextures(1, &texture);
}
~Texture() {
if (texture) {
glDeleteTextures(1, &texture);
}
}
void bind() {
glBindTexture(TextureType, texture);
}
static void unbind() {
glBindTexture(TextureType, 0);
}
void parameter(GLenum paramName, GLfloat f, GLenum target = TextureType ) {
glTexParameterf(target, paramName, f);
}
void parameter(GLenum paramName, GLint i, GLenum target = TextureType ) {
glTexParameteri(target, paramName, i);
}
void image2d(const glm::ivec2 & size, void * data,
GLint level = 0,
GLenum format = GL_RGB,
GLenum type = GL_UNSIGNED_BYTE) {
image2d(TextureType, size, data, level, format, type);
}
void image2d(GLenum target, const glm::ivec2 & size, void * data,
GLint level = 0,
GLenum format = GL_RGB,
GLenum type = GL_UNSIGNED_BYTE) {
GL_CHECK_ERROR;
glTexImage2D(target, level, TextureFormat, size.x, size.y, 0, format, type, data);
GL_CHECK_ERROR;
}
void storage2d(const glm::ivec2 & size, GLint levels = 1) {
glTexStorage2D(TextureType, levels, TextureFormat, size.x, size.y);
}
void generateMipmap() {
glGenerateMipmap(TextureType);
}
operator GLuint() {
return texture;
}
typedef std::shared_ptr<Texture<TextureType, TextureFormat> > Ptr;
};
typedef Texture<GL_TEXTURE_2D> Texture2d;
typedef Texture<GL_TEXTURE_2D, GL_DEPTH_COMPONENT16> Texture2dDepth;
typedef Texture<GL_TEXTURE_2D_MULTISAMPLE> Texture2dMs;
typedef Texture<GL_TEXTURE_3D> Texture3d;
typedef Texture<GL_TEXTURE_CUBE_MAP> TextureCubeMap;
typedef Texture2d::Ptr Texture2dPtr;
typedef Texture2dDepth::Ptr Texture2dDepthPtr;
typedef TextureCubeMap::Ptr TextureCubeMapPtr;
typedef Texture2dMs::Ptr Texture2dMsPtr;
typedef Texture2d::Ptr TexturePtr;
} // gl

71
GlVertexArrays.h Normal file
View File

@ -0,0 +1,71 @@
/************************************************************************************
Authors : Bradley Austin Davis <bdavis@saintandreas.org>
Copyright : Copyright Brad Davis. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
#pragma once
#ifndef GL_ZERO
#error "You must include the gl headers before including this file"
#endif
namespace gl {
class VertexArray {
GLuint object;
public:
VertexArray()
: object(0) {
}
~VertexArray() {
if (object) {
glDeleteVertexArrays(1, &object);
}
}
void bind() {
if (object == 0) {
glGenVertexArrays(1, &object);
}
glBindVertexArray(object);
}
static void draw(GLuint vertexCount, GLenum type = GL_TRIANGLES,
GLsizeiptr offset = 0, GLenum indexType = GL_UNSIGNED_INT) {
glDrawElements(type, vertexCount, indexType, (GLvoid*) offset);
}
void bindAndDraw(GLuint vertexCount, GLenum type = GL_TRIANGLES,
GLsizeiptr offset = 0, GLenum indexType = GL_UNSIGNED_INT) {
bind();
draw(vertexCount, type, offset, indexType);
unbind();
}
static void unbind() {
glBindVertexArray(0);
}
operator GLuint() {
return object;
}
};
typedef std::shared_ptr<VertexArray> VertexArrayPtr;
} // gl

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

4
README.md Normal file
View File

@ -0,0 +1,4 @@
gl
==
C++ header only OpenGL wrappers