Imported Upstream version 0.13.2+dsfg1

This commit is contained in:
Sebastian Ramacher 2016-02-24 00:16:51 +01:00
commit fb3990e9e5
2036 changed files with 287360 additions and 0 deletions

0
libobs-opengl/.gitignore vendored Normal file
View file

View file

@ -0,0 +1,99 @@
project(libobs-opengl)
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})
add_definitions(-DLIBOBS_EXPORTS)
if(WIN32)
set(libobs-opengl_PLATFORM_SOURCES
gl-windows.c)
elseif(APPLE)
set(libobs-opengl_PLATFORM_SOURCES
gl-cocoa.m)
set_source_files_properties(${libobs-opengl_PLATFORM_SOURCES}
PROPERTIES
LANGUAGE C)
find_library(COCOA Cocoa)
include_directories(${COCOA})
mark_as_advanced(COCOA)
find_library(IOSURF IOSurface)
include_directories(${IOSURF})
mark_as_advanced(${IOSURF})
set(libobs-opengl_PLATFORM_DEPS
${COCOA}
${IOSURF}
${OPENGL_gl_LIBRARY})
else() #This needs to change to be more specific to get ready for Wayland
find_package(XCB COMPONENTS XCB REQUIRED)
find_package(X11_XCB REQUIRED)
include_directories(
${XCB_INCLUDE_DIRS}
${X11_XCB_INCLUDE_DIRS})
add_definitions(
${XCB_DEFINITIONS}
${X11_XCB_DEFINITIONS})
set(libobs-opengl_PLATFORM_DEPS
${XCB_LIBRARIES}
${X11_XCB_LIBRARIES})
set(libobs-opengl_PLATFORM_SOURCES
gl-x11.c)
endif()
set(libobs-opengl_SOURCES
${libobs-opengl_PLATFORM_SOURCES}
gl-helpers.c
gl-indexbuffer.c
gl-shader.c
gl-shaderparser.c
gl-stagesurf.c
gl-subsystem.c
gl-texture2d.c
gl-texturecube.c
gl-vertexbuffer.c
gl-zstencil.c)
set(libobs-opengl_HEADERS
gl-helpers.h
gl-shaderparser.h
gl-subsystem.h)
if(WIN32 OR APPLE)
add_library(libobs-opengl MODULE
${libobs-opengl_SOURCES}
${libobs-opengl_HEADERS})
else()
add_library(libobs-opengl SHARED
${libobs-opengl_SOURCES}
${libobs-opengl_HEADERS})
endif()
if(WIN32 OR APPLE)
set_target_properties(libobs-opengl
PROPERTIES
OUTPUT_NAME libobs-opengl
PREFIX "")
else()
set_target_properties(libobs-opengl
PROPERTIES
OUTPUT_NAME obs-opengl
VERSION 0.0
SOVERSION 0
)
endif()
target_link_libraries(libobs-opengl
libobs
glad
${libobs-opengl_PLATFORM_DEPS})
install_obs_core(libobs-opengl)

298
libobs-opengl/gl-cocoa.m Normal file
View file

@ -0,0 +1,298 @@
/******************************************************************************
Copyright (C) 2013 by Ruwen Hahn <palana@stunned.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
#include <OpenGL/OpenGL.h>
#import <Cocoa/Cocoa.h>
#import <AppKit/AppKit.h>
//#include "util/darray.h"
struct gl_windowinfo {
NSView *view;
};
struct gl_platform {
NSOpenGLContext *context;
};
static NSOpenGLContext *gl_context_create(void)
{
unsigned attrib_count = 0;
#define ADD_ATTR(x) \
{ attributes[attrib_count++] = (NSOpenGLPixelFormatAttribute)x; }
#define ADD_ATTR2(x, y) { ADD_ATTR(x); ADD_ATTR(y); }
NSOpenGLPixelFormatAttribute attributes[40];
ADD_ATTR(NSOpenGLPFADoubleBuffer);
ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core);
ADD_ATTR(0);
#undef ADD_ATTR2
#undef ADD_ATTR
NSOpenGLPixelFormat *pf;
pf = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
if(!pf) {
blog(LOG_ERROR, "Failed to create pixel format");
return NULL;
}
NSOpenGLContext *context;
context = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:nil];
[pf release];
if(!context) {
blog(LOG_ERROR, "Failed to create context");
return NULL;
}
[context clearDrawable];
return context;
}
struct gl_platform *gl_platform_create(gs_device_t *device, uint32_t adapter)
{
struct gl_platform *plat = bzalloc(sizeof(struct gl_platform));
plat->context = gl_context_create();
if (!plat->context)
goto fail;
[plat->context makeCurrentContext];
if (!gladLoadGL())
goto fail;
return plat;
fail:
blog(LOG_ERROR, "gl_platform_create failed");
gl_platform_destroy(plat);
UNUSED_PARAMETER(device);
UNUSED_PARAMETER(adapter);
return NULL;
}
void gl_platform_destroy(struct gl_platform *platform)
{
if(!platform)
return;
[platform->context release];
platform->context = nil;
bfree(platform);
}
bool gl_platform_init_swapchain(struct gs_swap_chain *swap)
{
UNUSED_PARAMETER(swap);
return true;
}
void gl_platform_cleanup_swapchain(struct gs_swap_chain *swap)
{
UNUSED_PARAMETER(swap);
}
struct gl_windowinfo *gl_windowinfo_create(const struct gs_init_data *info)
{
if(!info)
return NULL;
if(!info->window.view)
return NULL;
struct gl_windowinfo *wi = bzalloc(sizeof(struct gl_windowinfo));
wi->view = info->window.view;
[info->window.view setWantsBestResolutionOpenGLSurface:YES];
return wi;
}
void gl_windowinfo_destroy(struct gl_windowinfo *wi)
{
if(!wi)
return;
wi->view = nil;
bfree(wi);
}
void gl_update(gs_device_t *device)
{
[device->plat->context update];
}
void device_enter_context(gs_device_t *device)
{
[device->plat->context makeCurrentContext];
}
void device_leave_context(gs_device_t *device)
{
UNUSED_PARAMETER(device);
[NSOpenGLContext clearCurrentContext];
}
void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swap)
{
if(device->cur_swap == swap)
return;
device->cur_swap = swap;
if (swap) {
[device->plat->context setView:swap->wi->view];
} else {
[device->plat->context clearDrawable];
}
}
void device_present(gs_device_t *device)
{
[device->plat->context flushBuffer];
}
void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width,
uint32_t *height)
{
if(width) *width = swap->info.cx;
if(height) *height = swap->info.cy;
}
gs_texture_t *device_texture_create_from_iosurface(gs_device_t *device,
void *iosurf)
{
IOSurfaceRef ref = (IOSurfaceRef)iosurf;
struct gs_texture_2d *tex = bzalloc(sizeof(struct gs_texture_2d));
OSType pf = IOSurfaceGetPixelFormat(ref);
if (pf != 'BGRA')
blog(LOG_ERROR, "Unexpected pixel format: %d (%c%c%c%c)", pf,
pf >> 24, pf >> 16, pf >> 8, pf);
const enum gs_color_format color_format = GS_BGRA;
tex->base.device = device;
tex->base.type = GS_TEXTURE_2D;
tex->base.format = GS_BGRA;
tex->base.levels = 1;
tex->base.gl_format = convert_gs_format(color_format);
tex->base.gl_internal_format = convert_gs_internal_format(color_format);
tex->base.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
tex->base.gl_target = GL_TEXTURE_RECTANGLE;
tex->base.is_dynamic = false;
tex->base.is_render_target = false;
tex->base.gen_mipmaps = false;
tex->width = IOSurfaceGetWidth(ref);
tex->height = IOSurfaceGetHeight(ref);
if (!gl_gen_textures(1, &tex->base.texture))
goto fail;
if (!gl_bind_texture(tex->base.gl_target, tex->base.texture))
goto fail;
CGLError err = CGLTexImageIOSurface2D(
[[NSOpenGLContext currentContext] CGLContextObj],
tex->base.gl_target,
tex->base.gl_internal_format,
tex->width, tex->height,
tex->base.gl_format,
tex->base.gl_type,
ref, 0);
if(err != kCGLNoError) {
blog(LOG_ERROR, "CGLTexImageIOSurface2D: %u, %s"
" (device_texture_create_from_iosurface)",
err, CGLErrorString(err));
gl_success("CGLTexImageIOSurface2D");
goto fail;
}
if (!gl_tex_param_i(tex->base.gl_target,
GL_TEXTURE_MAX_LEVEL, 0))
goto fail;
if (!gl_bind_texture(tex->base.gl_target, 0))
goto fail;
return (gs_texture_t*)tex;
fail:
gs_texture_destroy((gs_texture_t*)tex);
blog(LOG_ERROR, "device_texture_create_from_iosurface (GL) failed");
return NULL;
}
bool gs_texture_rebind_iosurface(gs_texture_t *texture, void *iosurf)
{
if (!texture)
return false;
if (!iosurf)
return false;
struct gs_texture_2d *tex = (struct gs_texture_2d*)texture;
IOSurfaceRef ref = (IOSurfaceRef)iosurf;
OSType pf = IOSurfaceGetPixelFormat(ref);
if (pf != 'BGRA')
blog(LOG_ERROR, "Unexpected pixel format: %d (%c%c%c%c)", pf,
pf >> 24, pf >> 16, pf >> 8, pf);
if (tex->width != IOSurfaceGetWidth(ref) ||
tex->height != IOSurfaceGetHeight(ref))
return false;
if (!gl_bind_texture(tex->base.gl_target, tex->base.texture))
return false;
CGLError err = CGLTexImageIOSurface2D(
[[NSOpenGLContext currentContext] CGLContextObj],
tex->base.gl_target,
tex->base.gl_internal_format,
tex->width, tex->height,
tex->base.gl_format,
tex->base.gl_type,
ref, 0);
if(err != kCGLNoError) {
blog(LOG_ERROR, "CGLTexImageIOSurface2D: %u, %s"
" (gs_texture_rebind_iosurface)",
err, CGLErrorString(err));
gl_success("CGLTexImageIOSurface2D");
return false;
}
if (!gl_bind_texture(tex->base.gl_target, 0))
return false;
return true;
}

172
libobs-opengl/gl-helpers.c Normal file
View file

@ -0,0 +1,172 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels,
GLenum format, GLint internal_format, bool compressed,
uint32_t width, uint32_t height, uint32_t size,
const uint8_t ***p_data)
{
bool success = true;
const uint8_t **data = p_data ? *p_data : NULL;
uint32_t i;
for (i = 0; i < num_levels; i++) {
if (compressed) {
glCompressedTexImage2D(target, i, internal_format,
width, height, 0, size,
data ? *data : NULL);
if (!gl_success("glCompressedTexImage2D"))
success = false;
} else {
glTexImage2D(target, i, internal_format, width, height,
0, format, type, data ? *data : NULL);
if (!gl_success("glTexImage2D"))
success = false;
}
if (data)
data++;
size /= 4;
width /= 2;
height /= 2;
if (width == 0) width = 1;
if (height == 0) height = 1;
}
if (data)
*p_data = data;
return success;
}
static bool gl_copy_fbo(struct gs_device *device,
GLuint dst, GLenum dst_target, uint32_t dst_x, uint32_t dst_y,
GLuint src, GLenum src_target, uint32_t src_x, uint32_t src_y,
uint32_t width, uint32_t height,
enum gs_color_format format)
{
struct fbo_info *fbo = get_fbo(device, width, height, format);
GLint last_fbo;
bool success = false;
if (!fbo)
return false;
if (!gl_get_integer_v(GL_READ_FRAMEBUFFER_BINDING, &last_fbo))
return false;
if (!gl_bind_framebuffer(GL_READ_FRAMEBUFFER, fbo->fbo))
return false;
if (!gl_bind_texture(dst_target, dst))
goto fail;
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0,
src_target, src, 0);
if (!gl_success("glFrameBufferTexture2D"))
goto fail;
glReadBuffer(GL_COLOR_ATTACHMENT0 + 0);
if (!gl_success("glReadBuffer"))
goto fail;
glCopyTexSubImage2D(dst_target, 0, dst_x, dst_y, src_x, src_y,
width, height);
if (!gl_success("glCopyTexSubImage2D"))
goto fail;
success = true;
fail:
if (!gl_bind_texture(dst_target, 0))
success = false;
if (!gl_bind_framebuffer(GL_READ_FRAMEBUFFER, last_fbo))
success = false;
return success;
}
bool gl_copy_texture(struct gs_device *device,
GLuint dst, GLenum dst_target, uint32_t dst_x, uint32_t dst_y,
GLuint src, GLenum src_target, uint32_t src_x, uint32_t src_y,
uint32_t width, uint32_t height, enum gs_color_format format)
{
bool success = false;
if (device->copy_type == COPY_TYPE_ARB) {
glCopyImageSubData(src, src_target, 0, src_x, src_y, 0,
dst, dst_target, 0, dst_x, dst_y, 0,
width, height, 1);
success = gl_success("glCopyImageSubData");
} else if (device->copy_type == COPY_TYPE_NV) {
glCopyImageSubDataNV(src, src_target, 0, src_x, src_y, 0,
dst, dst_target, 0, dst_x, dst_y, 0,
width, height, 1);
success = gl_success("glCopyImageSubDataNV");
} else if (device->copy_type == COPY_TYPE_FBO_BLIT) {
success = gl_copy_fbo(device, dst, dst_target, dst_x, dst_y,
src, src_target, src_x, src_y,
width, height, format);
if (!success)
blog(LOG_ERROR, "gl_copy_texture failed");
}
return success;
}
bool gl_create_buffer(GLenum target, GLuint *buffer, GLsizeiptr size,
const GLvoid *data, GLenum usage)
{
bool success;
if (!gl_gen_buffers(1, buffer))
return false;
if (!gl_bind_buffer(target, *buffer))
return false;
glBufferData(target, size, data, usage);
success = gl_success("glBufferData");
gl_bind_buffer(target, 0);
return success;
}
bool update_buffer(GLenum target, GLuint buffer, void *data, size_t size)
{
void *ptr;
bool success = true;
if (!gl_bind_buffer(target, buffer))
return false;
/* glMapBufferRange with these flags will actually give far better
* performance than a plain glMapBuffer call */
ptr = glMapBufferRange(target, 0, size,
GL_MAP_WRITE_BIT |
GL_MAP_INVALIDATE_BUFFER_BIT);
success = gl_success("glMapBufferRange");
if (success && ptr) {
memcpy(ptr, data, size);
glUnmapBuffer(target);
}
gl_bind_buffer(target, 0);
return success;
}

161
libobs-opengl/gl-helpers.h Normal file
View file

@ -0,0 +1,161 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
/*
* Okay, so GL error handling is.. unclean to work with. I don't want
* to have to keep typing out the same stuff over and over again do I'll just
* make a bunch of helper functions to make it a bit easier to handle errors
*/
static inline bool gl_success(const char *funcname)
{
GLenum errorcode = glGetError();
if (errorcode != GL_NO_ERROR) {
blog(LOG_ERROR, "%s failed, glGetError returned 0x%X",
funcname, errorcode);
return false;
}
return true;
}
static inline bool gl_gen_textures(GLsizei num_texture, GLuint *textures)
{
glGenTextures(num_texture, textures);
return gl_success("glGenTextures");
}
static inline bool gl_bind_texture(GLenum target, GLuint texture)
{
glBindTexture(target, texture);
return gl_success("glBindTexture");
}
static inline void gl_delete_textures(GLsizei num_buffers, GLuint *buffers)
{
glDeleteTextures(num_buffers, buffers);
gl_success("glDeleteTextures");
}
static inline bool gl_gen_buffers(GLsizei num_buffers, GLuint *buffers)
{
glGenBuffers(num_buffers, buffers);
return gl_success("glGenBuffers");
}
static inline bool gl_bind_buffer(GLenum target, GLuint buffer)
{
glBindBuffer(target, buffer);
return gl_success("glBindBuffer");
}
static inline void gl_delete_buffers(GLsizei num_buffers, GLuint *buffers)
{
glDeleteBuffers(num_buffers, buffers);
gl_success("glDeleteBuffers");
}
static inline bool gl_gen_vertex_arrays(GLsizei num_arrays, GLuint *arrays)
{
glGenVertexArrays(num_arrays, arrays);
return gl_success("glGenVertexArrays");
}
static inline bool gl_bind_vertex_array(GLuint array)
{
glBindVertexArray(array);
return gl_success("glBindVertexArray");
}
static inline void gl_delete_vertex_arrays(GLsizei num_arrays, GLuint *arrays)
{
glDeleteVertexArrays(num_arrays, arrays);
gl_success("glDeleteVertexArrays");
}
static inline bool gl_bind_renderbuffer(GLenum target, GLuint buffer)
{
glBindRenderbuffer(target, buffer);
return gl_success("glBindRendebuffer");
}
static inline bool gl_bind_framebuffer(GLenum target, GLuint buffer)
{
glBindFramebuffer(target, buffer);
return gl_success("glBindFramebuffer");
}
static inline bool gl_tex_param_f(GLenum target, GLenum param, GLfloat val)
{
glTexParameterf(target, param, val);
return gl_success("glTexParameterf");
}
static inline bool gl_tex_param_i(GLenum target, GLenum param, GLint val)
{
glTexParameteri(target, param, val);
return gl_success("glTexParameteri");
}
static inline bool gl_active_texture(GLenum texture_id)
{
glActiveTexture(texture_id);
return gl_success("glActiveTexture");
}
static inline bool gl_enable(GLenum capability)
{
glEnable(capability);
return gl_success("glEnable");
}
static inline bool gl_disable(GLenum capability)
{
glDisable(capability);
return gl_success("glDisable");
}
static inline bool gl_cull_face(GLenum faces)
{
glCullFace(faces);
return gl_success("glCullFace");
}
static inline bool gl_get_integer_v(GLenum pname, GLint *params)
{
glGetIntegerv(pname, params);
return gl_success("glGetIntegerv");
}
extern bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels,
GLenum format, GLint internal_format, bool compressed,
uint32_t width, uint32_t height, uint32_t size,
const uint8_t ***p_data);
extern bool gl_copy_texture(struct gs_device *device,
GLuint dst, GLenum dst_target, uint32_t dst_x, uint32_t dst_y,
GLuint src, GLenum src_target, uint32_t src_x, uint32_t src_y,
uint32_t width, uint32_t height,
enum gs_color_format format);
extern bool gl_create_buffer(GLenum target, GLuint *buffer, GLsizeiptr size,
const GLvoid *data, GLenum usage);
extern bool update_buffer(GLenum target, GLuint buffer, void *data,
size_t size);

View file

@ -0,0 +1,113 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
static inline bool init_ib(struct gs_index_buffer *ib)
{
GLenum usage = ib->dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW;
bool success;
success = gl_create_buffer(GL_ARRAY_BUFFER, &ib->buffer, ib->size,
ib->data, usage);
if (!ib->dynamic) {
bfree(ib->data);
ib->data = NULL;
}
return success;
}
gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device,
enum gs_index_type type, void *indices, size_t num,
uint32_t flags)
{
struct gs_index_buffer *ib = bzalloc(sizeof(struct gs_index_buffer));
size_t width = type == GS_UNSIGNED_LONG ? sizeof(long) : sizeof(short);
ib->device = device;
ib->data = indices;
ib->dynamic = flags & GS_DYNAMIC;
ib->num = num;
ib->width = width;
ib->size = width * num;
ib->type = type;
ib->gl_type = type == GS_UNSIGNED_LONG ? GL_UNSIGNED_INT :
GL_UNSIGNED_SHORT;
if (!init_ib(ib)) {
blog(LOG_ERROR, "device_indexbuffer_create (GL) failed");
gs_indexbuffer_destroy(ib);
return NULL;
}
return ib;
}
void gs_indexbuffer_destroy(gs_indexbuffer_t *ib)
{
if (ib) {
if (ib->buffer)
gl_delete_buffers(1, &ib->buffer);
bfree(ib->data);
bfree(ib);
}
}
void gs_indexbuffer_flush(gs_indexbuffer_t *ib)
{
if (!ib->dynamic) {
blog(LOG_ERROR, "Index buffer is not dynamic");
goto fail;
}
if (!update_buffer(GL_ARRAY_BUFFER, ib->buffer, ib->data, ib->size))
goto fail;
return;
fail:
blog(LOG_ERROR, "gs_indexbuffer_flush (GL) failed");
}
void *gs_indexbuffer_get_data(const gs_indexbuffer_t *ib)
{
return ib->data;
}
size_t gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *ib)
{
return ib->num;
}
enum gs_index_type gs_indexbuffer_get_type(const gs_indexbuffer_t *ib)
{
return ib->type;
}
void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *ib)
{
if (ib == device->cur_index_buffer)
return;
device->cur_index_buffer = ib;
if (!gl_bind_buffer(GL_ELEMENT_ARRAY_BUFFER, ib->buffer))
blog(LOG_ERROR, "device_load_indexbuffer (GL) failed");
}

722
libobs-opengl/gl-shader.c Normal file
View file

@ -0,0 +1,722 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <assert.h>
#include <graphics/vec2.h>
#include <graphics/vec3.h>
#include <graphics/vec4.h>
#include <graphics/matrix3.h>
#include <graphics/matrix4.h>
#include "gl-subsystem.h"
#include "gl-shaderparser.h"
static inline void shader_param_init(struct gs_shader_param *param)
{
memset(param, 0, sizeof(struct gs_shader_param));
}
static inline void shader_param_free(struct gs_shader_param *param)
{
bfree(param->name);
da_free(param->cur_value);
da_free(param->def_value);
}
static inline void shader_attrib_free(struct shader_attrib *attrib)
{
bfree(attrib->name);
}
static void gl_get_shader_info(GLuint shader, const char *file,
char **error_string)
{
char *errors;
GLint info_len = 0;
GLsizei chars_written = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_len);
if (!gl_success("glGetProgramiv") || !info_len)
return;
errors = bzalloc(info_len+1);
glGetShaderInfoLog(shader, info_len, &chars_written, errors);
gl_success("glGetShaderInfoLog");
blog(LOG_DEBUG, "Compiler warnings/errors for %s:\n%s", file, errors);
if (error_string)
*error_string = errors;
else
bfree(errors);
}
static bool gl_add_param(struct gs_shader *shader, struct shader_var *var,
GLint *texture_id)
{
struct gs_shader_param param = {0};
param.array_count = var->array_count;
param.name = bstrdup(var->name);
param.shader = shader;
param.type = get_shader_param_type(var->type);
if (param.type == GS_SHADER_PARAM_TEXTURE) {
param.sampler_id = var->gl_sampler_id;
param.texture_id = (*texture_id)++;
} else {
param.changed = true;
}
da_move(param.def_value, var->default_val);
da_copy(param.cur_value, param.def_value);
da_push_back(shader->params, &param);
return true;
}
static inline bool gl_add_params(struct gs_shader *shader,
struct gl_shader_parser *glsp)
{
size_t i;
GLint tex_id = 0;
for (i = 0; i < glsp->parser.params.num; i++)
if (!gl_add_param(shader, glsp->parser.params.array+i, &tex_id))
return false;
shader->viewproj = gs_shader_get_param_by_name(shader, "ViewProj");
shader->world = gs_shader_get_param_by_name(shader, "World");
return true;
}
static inline void gl_add_sampler(struct gs_shader *shader,
struct shader_sampler *sampler)
{
gs_samplerstate_t *new_sampler;
struct gs_sampler_info info;
shader_sampler_convert(sampler, &info);
new_sampler = device_samplerstate_create(shader->device, &info);
da_push_back(shader->samplers, &new_sampler);
}
static inline void gl_add_samplers(struct gs_shader *shader,
struct gl_shader_parser *glsp)
{
size_t i;
for (i = 0; i < glsp->parser.samplers.num; i++) {
struct shader_sampler *sampler = glsp->parser.samplers.array+i;
gl_add_sampler(shader, sampler);
}
}
static void get_attrib_type(const char *mapping, enum attrib_type *type,
size_t *index)
{
if (strcmp(mapping, "POSITION") == 0) {
*type = ATTRIB_POSITION;
} else if (strcmp(mapping, "NORMAL") == 0) {
*type = ATTRIB_NORMAL;
} else if (strcmp(mapping, "TANGENT") == 0) {
*type = ATTRIB_TANGENT;
} else if (strcmp(mapping, "COLOR") == 0) {
*type = ATTRIB_COLOR;
} else if (astrcmp_n(mapping, "TEXCOORD", 8) == 0) {
*type = ATTRIB_TEXCOORD;
*index = (*(mapping+8)) - '0';
return;
} else if (strcmp(mapping, "TARGET") == 0) {
*type = ATTRIB_TARGET;
}
*index = 0;
}
static inline bool gl_process_attrib(struct gs_shader *program,
struct gl_parser_attrib *pa)
{
struct shader_attrib attrib = {0};
/* don't parse output attributes */
if (!pa->input)
return true;
get_attrib_type(pa->mapping, &attrib.type, &attrib.index);
attrib.name = pa->name.array;
pa->name.array = NULL;
pa->name.len = 0;
pa->name.capacity = 0;
da_push_back(program->attribs, &attrib);
return true;
}
static inline bool gl_process_attribs(struct gs_shader *shader,
struct gl_shader_parser *glsp)
{
size_t i;
for (i = 0; i < glsp->attribs.num; i++) {
struct gl_parser_attrib *pa = glsp->attribs.array+i;
if (!gl_process_attrib(shader, pa))
return false;
}
return true;
}
static bool gl_shader_init(struct gs_shader *shader,
struct gl_shader_parser *glsp,
const char *file, char **error_string)
{
GLenum type = convert_shader_type(shader->type);
int compiled = 0;
bool success = true;
shader->obj = glCreateShader(type);
if (!gl_success("glCreateShader") || !shader->obj)
return false;
glShaderSource(shader->obj, 1, (const GLchar**)&glsp->gl_string.array,
0);
if (!gl_success("glShaderSource"))
return false;
glCompileShader(shader->obj);
if (!gl_success("glCompileShader"))
return false;
#if 0
blog(LOG_DEBUG, "+++++++++++++++++++++++++++++++++++");
blog(LOG_DEBUG, " GL shader string for: %s", file);
blog(LOG_DEBUG, "-----------------------------------");
blog(LOG_DEBUG, "%s", glsp->gl_string.array);
blog(LOG_DEBUG, "+++++++++++++++++++++++++++++++++++");
#endif
glGetShaderiv(shader->obj, GL_COMPILE_STATUS, &compiled);
if (!gl_success("glGetShaderiv"))
return false;
if (!compiled)
success = false;
gl_get_shader_info(shader->obj, file, error_string);
if (success)
success = gl_add_params(shader, glsp);
/* Only vertex shaders actually require input attributes */
if (success && shader->type == GS_SHADER_VERTEX)
success = gl_process_attribs(shader, glsp);
if (success)
gl_add_samplers(shader, glsp);
return success;
}
static struct gs_shader *shader_create(gs_device_t *device,
enum gs_shader_type type, const char *shader_str,
const char *file, char **error_string)
{
struct gs_shader *shader = bzalloc(sizeof(struct gs_shader));
struct gl_shader_parser glsp;
bool success = true;
shader->device = device;
shader->type = type;
gl_shader_parser_init(&glsp, type);
if (!gl_shader_parse(&glsp, shader_str, file))
success = false;
else
success = gl_shader_init(shader, &glsp, file, error_string);
if (!success) {
gs_shader_destroy(shader);
shader = NULL;
}
gl_shader_parser_free(&glsp);
return shader;
}
gs_shader_t *device_vertexshader_create(gs_device_t *device,
const char *shader, const char *file,
char **error_string)
{
struct gs_shader *ptr;
ptr = shader_create(device, GS_SHADER_VERTEX, shader, file,
error_string);
if (!ptr)
blog(LOG_ERROR, "device_vertexshader_create (GL) failed");
return ptr;
}
gs_shader_t *device_pixelshader_create(gs_device_t *device,
const char *shader, const char *file,
char **error_string)
{
struct gs_shader *ptr;
ptr = shader_create(device, GS_SHADER_PIXEL, shader, file,
error_string);
if (!ptr)
blog(LOG_ERROR, "device_pixelshader_create (GL) failed");
return ptr;
}
static void remove_program_references(struct gs_shader *shader)
{
struct gs_program *program = shader->device->first_program;
while (program) {
struct gs_program *next = program->next;
bool destroy = false;
if (shader->type == GS_SHADER_VERTEX &&
program->vertex_shader == shader)
destroy = true;
else if (shader->type == GS_SHADER_PIXEL &&
program->pixel_shader == shader)
destroy = true;
if (destroy)
gs_program_destroy(program);
program = next;
}
}
void gs_shader_destroy(gs_shader_t *shader)
{
size_t i;
if (!shader)
return;
remove_program_references(shader);
for (i = 0; i < shader->attribs.num; i++)
shader_attrib_free(shader->attribs.array+i);
for (i = 0; i < shader->samplers.num; i++)
gs_samplerstate_destroy(shader->samplers.array[i]);
for (i = 0; i < shader->params.num; i++)
shader_param_free(shader->params.array+i);
if (shader->obj) {
glDeleteShader(shader->obj);
gl_success("glDeleteShader");
}
da_free(shader->samplers);
da_free(shader->params);
da_free(shader->attribs);
bfree(shader);
}
int gs_shader_get_num_params(const gs_shader_t *shader)
{
return (int)shader->params.num;
}
gs_sparam_t *gs_shader_get_param_by_idx(gs_shader_t *shader, uint32_t param)
{
assert(param < shader->params.num);
return shader->params.array+param;
}
gs_sparam_t *gs_shader_get_param_by_name(gs_shader_t *shader, const char *name)
{
size_t i;
for (i = 0; i < shader->params.num; i++) {
struct gs_shader_param *param = shader->params.array+i;
if (strcmp(param->name, name) == 0)
return param;
}
return NULL;
}
gs_sparam_t *gs_shader_get_viewproj_matrix(const gs_shader_t *shader)
{
return shader->viewproj;
}
gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader)
{
return shader->world;
}
void gs_shader_get_param_info(const gs_sparam_t *param,
struct gs_shader_param_info *info)
{
info->type = param->type;
info->name = param->name;
}
void gs_shader_set_bool(gs_sparam_t *param, bool val)
{
int int_val = val;
da_copy_array(param->cur_value, &int_val, sizeof(int_val));
}
void gs_shader_set_float(gs_sparam_t *param, float val)
{
da_copy_array(param->cur_value, &val, sizeof(val));
}
void gs_shader_set_int(gs_sparam_t *param, int val)
{
da_copy_array(param->cur_value, &val, sizeof(val));
}
void gs_shader_set_matrix3(gs_sparam_t *param, const struct matrix3 *val)
{
struct matrix4 mat;
matrix4_from_matrix3(&mat, val);
da_copy_array(param->cur_value, &mat, sizeof(mat));
}
void gs_shader_set_matrix4(gs_sparam_t *param, const struct matrix4 *val)
{
da_copy_array(param->cur_value, val, sizeof(*val));
}
void gs_shader_set_vec2(gs_sparam_t *param, const struct vec2 *val)
{
da_copy_array(param->cur_value, val->ptr, sizeof(*val));
}
void gs_shader_set_vec3(gs_sparam_t *param, const struct vec3 *val)
{
da_copy_array(param->cur_value, val->ptr, sizeof(*val));
}
void gs_shader_set_vec4(gs_sparam_t *param, const struct vec4 *val)
{
da_copy_array(param->cur_value, val->ptr, sizeof(*val));
}
void gs_shader_set_texture(gs_sparam_t *param, gs_texture_t *val)
{
param->texture = val;
}
static inline bool validate_param(struct program_param *pp,
size_t expected_size)
{
if (pp->param->cur_value.num != expected_size) {
blog(LOG_ERROR, "Parameter '%s' set to invalid size %u, "
"expected %u",
pp->param->name,
(unsigned int)pp->param->cur_value.num,
(unsigned int)expected_size);
return false;
}
return true;
}
static void program_set_param_data(struct gs_program *program,
struct program_param *pp)
{
void *array = pp->param->cur_value.array;
if (pp->param->type == GS_SHADER_PARAM_BOOL ||
pp->param->type == GS_SHADER_PARAM_INT) {
if (validate_param(pp, sizeof(int))) {
glUniform1iv(pp->obj, 1, (int*)array);
gl_success("glUniform1iv");
}
} else if (pp->param->type == GS_SHADER_PARAM_FLOAT) {
if (validate_param(pp, sizeof(float))) {
glUniform1fv(pp->obj, 1, (float*)array);
gl_success("glUniform1fv");
}
} else if (pp->param->type == GS_SHADER_PARAM_VEC2) {
if (validate_param(pp, sizeof(struct vec2))) {
glUniform2fv(pp->obj, 1, (float*)array);
gl_success("glUniform2fv");
}
} else if (pp->param->type == GS_SHADER_PARAM_VEC3) {
if (validate_param(pp, sizeof(float) * 3)) {
glUniform3fv(pp->obj, 1, (float*)array);
gl_success("glUniform3fv");
}
} else if (pp->param->type == GS_SHADER_PARAM_VEC4) {
if (validate_param(pp, sizeof(struct vec4))) {
glUniform4fv(pp->obj, 1, (float*)array);
gl_success("glUniform4fv");
}
} else if (pp->param->type == GS_SHADER_PARAM_MATRIX4X4) {
if (validate_param(pp, sizeof(struct matrix4))) {
glUniformMatrix4fv(pp->obj, 1, false,
(float*)array);
gl_success("glUniformMatrix4fv");
}
} else if (pp->param->type == GS_SHADER_PARAM_TEXTURE) {
glUniform1i(pp->obj, pp->param->texture_id);
device_load_texture(program->device, pp->param->texture,
pp->param->texture_id);
}
}
void program_update_params(struct gs_program *program)
{
for (size_t i = 0; i < program->params.num; i++) {
struct program_param *pp = program->params.array + i;
program_set_param_data(program, pp);
}
}
static void print_link_errors(GLuint program)
{
char *errors = NULL;
GLint info_len = 0;
GLsizei chars_written = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_len);
if (!gl_success("glGetProgramiv") || !info_len)
return;
errors = calloc(1, info_len+1);
glGetProgramInfoLog(program, info_len, &chars_written, errors);
gl_success("glGetShaderInfoLog");
blog(LOG_DEBUG, "Linker warnings/errors:\n%s", errors);
free(errors);
}
static bool assign_program_attrib(struct gs_program *program,
struct shader_attrib *attrib)
{
GLint attrib_obj = glGetAttribLocation(program->obj, attrib->name);
if (!gl_success("glGetAttribLocation"))
return false;
if (attrib_obj == -1) {
blog(LOG_ERROR, "glGetAttribLocation: Could not find "
"attribute '%s'", attrib->name);
return false;
}
da_push_back(program->attribs, &attrib_obj);
return true;
}
static inline bool assign_program_attribs(struct gs_program *program)
{
struct gs_shader *shader = program->vertex_shader;
for (size_t i = 0; i < shader->attribs.num; i++) {
struct shader_attrib *attrib = shader->attribs.array + i;
if (!assign_program_attrib(program, attrib))
return false;
}
return true;
}
static bool assign_program_param(struct gs_program *program,
struct gs_shader_param *param)
{
struct program_param info;
info.obj = glGetUniformLocation(program->obj, param->name);
if (!gl_success("glGetUniformLocation"))
return false;
if (info.obj == -1) {
return true;
}
info.param = param;
da_push_back(program->params, &info);
return true;
}
static inline bool assign_program_shader_params(struct gs_program *program,
struct gs_shader *shader)
{
for (size_t i = 0; i < shader->params.num; i++) {
struct gs_shader_param *param = shader->params.array + i;
if (!assign_program_param(program, param))
return false;
}
return true;
}
static inline bool assign_program_params(struct gs_program *program)
{
if (!assign_program_shader_params(program, program->vertex_shader))
return false;
if (!assign_program_shader_params(program, program->pixel_shader))
return false;
return true;
}
struct gs_program *gs_program_create(struct gs_device *device)
{
struct gs_program *program = bzalloc(sizeof(*program));
int linked = false;
program->device = device;
program->vertex_shader = device->cur_vertex_shader;
program->pixel_shader = device->cur_pixel_shader;
program->obj = glCreateProgram();
if (!gl_success("glCreateProgram"))
goto error_detach_neither;
glAttachShader(program->obj, program->vertex_shader->obj);
if (!gl_success("glAttachShader (vertex)"))
goto error_detach_neither;
glAttachShader(program->obj, program->pixel_shader->obj);
if (!gl_success("glAttachShader (pixel)"))
goto error_detach_vertex;
glLinkProgram(program->obj);
if (!gl_success("glLinkProgram"))
goto error;
glGetProgramiv(program->obj, GL_LINK_STATUS, &linked);
if (!gl_success("glGetProgramiv"))
goto error;
if (linked == GL_FALSE) {
print_link_errors(program->obj);
goto error;
}
if (!assign_program_attribs(program))
goto error;
if (!assign_program_params(program))
goto error;
glDetachShader(program->obj, program->vertex_shader->obj);
gl_success("glDetachShader (vertex)");
glDetachShader(program->obj, program->pixel_shader->obj);
gl_success("glDetachShader (pixel)");
program->next = device->first_program;
program->prev_next = &device->first_program;
device->first_program = program;
if (program->next)
program->next->prev_next = &program->next;
return program;
error:
glDetachShader(program->obj, program->pixel_shader->obj);
gl_success("glDetachShader (pixel)");
error_detach_vertex:
glDetachShader(program->obj, program->vertex_shader->obj);
gl_success("glDetachShader (vertex)");
error_detach_neither:
gs_program_destroy(program);
return NULL;
}
void gs_program_destroy(struct gs_program *program)
{
if (!program)
return;
if (program->device->cur_program == program) {
program->device->cur_program = 0;
glUseProgram(0);
gl_success("glUseProgram (zero)");
}
da_free(program->attribs);
da_free(program->params);
if (program->next)
program->next->prev_next = program->prev_next;
if (program->prev_next)
*program->prev_next = program->next;
glDeleteProgram(program->obj);
gl_success("glDeleteProgram");
bfree(program);
}
void gs_shader_set_val(gs_sparam_t *param, const void *val, size_t size)
{
int count = param->array_count;
size_t expected_size = 0;
if (!count)
count = 1;
switch ((uint32_t)param->type) {
case GS_SHADER_PARAM_FLOAT: expected_size = sizeof(float); break;
case GS_SHADER_PARAM_BOOL:
case GS_SHADER_PARAM_INT: expected_size = sizeof(int); break;
case GS_SHADER_PARAM_VEC2: expected_size = sizeof(float)*2; break;
case GS_SHADER_PARAM_VEC3: expected_size = sizeof(float)*3; break;
case GS_SHADER_PARAM_VEC4: expected_size = sizeof(float)*4; break;
case GS_SHADER_PARAM_MATRIX4X4: expected_size = sizeof(float)*4*4;break;
case GS_SHADER_PARAM_TEXTURE: expected_size = sizeof(void*); break;
default: expected_size = 0;
}
expected_size *= count;
if (!expected_size)
return;
if (expected_size != size) {
blog(LOG_ERROR, "gs_shader_set_val (GL): Size of shader "
"param does not match the size of the input");
return;
}
if (param->type == GS_SHADER_PARAM_TEXTURE)
gs_shader_set_texture(param, *(gs_texture_t**)val);
else
da_copy_array(param->cur_value, val, size);
}
void gs_shader_set_default(gs_sparam_t *param)
{
gs_shader_set_val(param, param->def_value.array, param->def_value.num);
}

View file

@ -0,0 +1,664 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
#include "gl-shaderparser.h"
static void gl_write_function_contents(struct gl_shader_parser *glsp,
struct cf_token **p_token, const char *end);
static inline struct shader_var *sp_getparam(struct gl_shader_parser *glsp,
struct cf_token *token)
{
size_t i;
for (i = 0; i < glsp->parser.params.num; i++) {
struct shader_var *param = glsp->parser.params.array+i;
if (strref_cmp(&token->str, param->name) == 0)
return param;
}
return NULL;
}
static inline size_t sp_getsampler(struct gl_shader_parser *glsp,
struct cf_token *token)
{
size_t i;
for (i = 0; i < glsp->parser.samplers.num; i++) {
struct shader_sampler *sampler = glsp->parser.samplers.array+i;
if (strref_cmp(&token->str, sampler->name) == 0)
return i;
}
return -1;
}
static inline int cmp_type(const char *name, const size_t name_len,
const char *type, const size_t type_len)
{
size_t min_len = (name_len < type_len) ? type_len : name_len;
return astrcmp_n(name, type, min_len);
}
static bool gl_write_type_n(struct gl_shader_parser *glsp,
const char *type, size_t len)
{
if (cmp_type(type, len, "float2", 6) == 0)
dstr_cat(&glsp->gl_string, "vec2");
else if (cmp_type(type, len, "float3", 6) == 0)
dstr_cat(&glsp->gl_string, "vec3");
else if (cmp_type(type, len, "float4", 6) == 0)
dstr_cat(&glsp->gl_string, "vec4");
else if (cmp_type(type, len, "float3x3", 8) == 0)
dstr_cat(&glsp->gl_string, "mat3x3");
else if (cmp_type(type, len, "float3x4", 8) == 0)
dstr_cat(&glsp->gl_string, "mat3x4");
else if (cmp_type(type, len, "float4x4", 8) == 0)
dstr_cat(&glsp->gl_string, "mat4x4");
else if (cmp_type(type, len, "texture2d", 9) == 0)
dstr_cat(&glsp->gl_string, "sampler2D");
else if (cmp_type(type, len, "texture3d", 9) == 0)
dstr_cat(&glsp->gl_string, "sampler3D");
else if (cmp_type(type, len, "texture_cube", 12) == 0)
dstr_cat(&glsp->gl_string, "samplerCube");
else if (cmp_type(type, len, "texture_rect", 12) == 0)
dstr_cat(&glsp->gl_string, "sampler2DRect");
else
return false;
return true;
}
static inline void gl_write_type(struct gl_shader_parser *glsp,
const char *type)
{
if (!gl_write_type_n(glsp, type, strlen(type)))
dstr_cat(&glsp->gl_string, type);
}
static inline bool gl_write_type_token(struct gl_shader_parser *glsp,
struct cf_token *token)
{
return gl_write_type_n(glsp, token->str.array, token->str.len);
}
static void gl_write_var(struct gl_shader_parser *glsp, struct shader_var *var)
{
if (var->var_type == SHADER_VAR_UNIFORM)
dstr_cat(&glsp->gl_string, "uniform ");
else if (var->var_type == SHADER_VAR_CONST)
dstr_cat(&glsp->gl_string, "const ");
gl_write_type(glsp, var->type);
dstr_cat(&glsp->gl_string, " ");
dstr_cat(&glsp->gl_string, var->name);
}
static inline void gl_write_params(struct gl_shader_parser *glsp)
{
size_t i;
for (i = 0; i < glsp->parser.params.num; i++) {
struct shader_var *var = glsp->parser.params.array+i;
gl_write_var(glsp, var);
dstr_cat(&glsp->gl_string, ";\n");
}
dstr_cat(&glsp->gl_string, "\n");
}
static void gl_write_storage_var(struct gl_shader_parser *glsp,
struct shader_var *var, bool input, const char *prefix);
/* unwraps a structure that's used for input/output */
static void gl_unwrap_storage_struct(struct gl_shader_parser *glsp,
struct shader_struct *st, const char *name, bool input,
const char *prefix)
{
struct dstr prefix_str;
size_t i;
dstr_init(&prefix_str);
if (prefix)
dstr_copy(&prefix_str, prefix);
dstr_cat(&prefix_str, name);
dstr_cat(&prefix_str, "_");
for (i = 0; i < st->vars.num; i++) {
struct shader_var *st_var = st->vars.array+i;
gl_write_storage_var(glsp, st_var, input, prefix_str.array);
}
dstr_free(&prefix_str);
}
static void gl_write_storage_var(struct gl_shader_parser *glsp,
struct shader_var *var, bool input, const char *prefix)
{
struct shader_struct *st = shader_parser_getstruct(&glsp->parser,
var->type);
if (st) {
gl_unwrap_storage_struct(glsp, st, var->name, input, prefix);
} else {
struct gl_parser_attrib attrib;
gl_parser_attrib_init(&attrib);
dstr_cat(&glsp->gl_string, input ? "in " : "out ");
if (prefix)
dstr_cat(&attrib.name, prefix);
dstr_cat(&attrib.name, var->name);
gl_write_type(glsp, var->type);
dstr_cat(&glsp->gl_string, " ");
dstr_cat_dstr(&glsp->gl_string, &attrib.name);
dstr_cat(&glsp->gl_string, ";\n");
attrib.input = input;
attrib.mapping = var->mapping;
da_push_back(glsp->attribs, &attrib);
}
}
static inline void gl_write_inputs(struct gl_shader_parser *glsp,
struct shader_func *main)
{
size_t i;
for (i = 0; i < main->params.num; i++)
gl_write_storage_var(glsp, main->params.array+i, true,
"inputval_");
dstr_cat(&glsp->gl_string, "\n");
}
static void gl_write_outputs(struct gl_shader_parser *glsp,
struct shader_func *main)
{
struct shader_var var = {0};
var.type = main->return_type;
var.name = "outputval";
if (main->mapping)
var.mapping = main->mapping;
gl_write_storage_var(glsp, &var, false, NULL);
dstr_cat(&glsp->gl_string, "\n");
}
static void gl_write_struct(struct gl_shader_parser *glsp,
struct shader_struct *st)
{
size_t i;
dstr_cat(&glsp->gl_string, "struct ");
dstr_cat(&glsp->gl_string, st->name);
dstr_cat(&glsp->gl_string, " {\n");
for (i = 0; i < st->vars.num; i++) {
struct shader_var *var = st->vars.array+i;
dstr_cat(&glsp->gl_string, "\t");
gl_write_var(glsp, var);
dstr_cat(&glsp->gl_string, ";\n");
}
dstr_cat(&glsp->gl_string, "};\n\n");
}
static void gl_write_interface_block(struct gl_shader_parser *glsp)
{
if (glsp->type == GS_SHADER_VERTEX) {
dstr_cat(&glsp->gl_string, "out gl_PerVertex {\n"
"\tvec4 gl_Position;\n};\n\n");
}
}
static inline void gl_write_structs(struct gl_shader_parser *glsp)
{
size_t i;
for (i = 0; i < glsp->parser.structs.num; i++) {
struct shader_struct *st = glsp->parser.structs.array+i;
gl_write_struct(glsp, st);
}
}
/*
* NOTE: HLSL-> GLSL intrinsic conversions
* atan2 -> atan
* clip -> (unsupported)
* ddx -> dFdx
* ddy -> dFdy
* fmod -> mod (XXX: these are different if sign is negative)
* frac -> fract
* lerp -> mix
* lit -> (unsupported)
* log10 -> (unsupported)
* mul -> (change to operator)
* rsqrt -> inversesqrt
* saturate -> (use clamp)
* tex* -> texture
* tex*grad -> textureGrad
* tex*lod -> textureLod
* tex*bias -> (use optional 'bias' value)
* tex*proj -> textureProj
*
* All else can be left as-is
*/
static bool gl_write_mul(struct gl_shader_parser *glsp,
struct cf_token **p_token)
{
struct cf_parser *cfp = &glsp->parser.cfp;
cfp->cur_token = *p_token;
if (!cf_next_token(cfp)) return false;
if (!cf_token_is(cfp, "(")) return false;
dstr_cat(&glsp->gl_string, "(");
gl_write_function_contents(glsp, &cfp->cur_token, ",");
dstr_cat(&glsp->gl_string, ") * (");
cf_next_token(cfp);
gl_write_function_contents(glsp, &cfp->cur_token, ")");
dstr_cat(&glsp->gl_string, "))");
*p_token = cfp->cur_token;
return true;
}
static bool gl_write_saturate(struct gl_shader_parser *glsp,
struct cf_token **p_token)
{
struct cf_parser *cfp = &glsp->parser.cfp;
cfp->cur_token = *p_token;
if (!cf_next_token(cfp)) return false;
if (!cf_token_is(cfp, "(")) return false;
dstr_cat(&glsp->gl_string, "clamp");
gl_write_function_contents(glsp, &cfp->cur_token, ")");
dstr_cat(&glsp->gl_string, ", 0.0, 1.0)");
*p_token = cfp->cur_token;
return true;
}
static inline bool gl_write_texture_call(struct gl_shader_parser *glsp,
struct shader_var *var, const char *call)
{
struct cf_parser *cfp = &glsp->parser.cfp;
size_t sampler_id = (size_t)-1;
if (!cf_next_token(cfp)) return false;
if (!cf_token_is(cfp, "(")) return false;
if (!cf_next_token(cfp)) return false;
sampler_id = sp_getsampler(glsp, cfp->cur_token);
if (sampler_id == (size_t)-1) return false;
if (!cf_next_token(cfp)) return false;
if (!cf_token_is(cfp, ",")) return false;
var->gl_sampler_id = sampler_id;
dstr_cat(&glsp->gl_string, call);
dstr_cat(&glsp->gl_string, "(");
dstr_cat(&glsp->gl_string, var->name);
dstr_cat(&glsp->gl_string, ", ");
return true;
}
/* processes texture.Sample(sampler, texcoord) */
static bool gl_write_texture_code(struct gl_shader_parser *glsp,
struct cf_token **p_token, struct shader_var *var)
{
struct cf_parser *cfp = &glsp->parser.cfp;
bool written = false;
cfp->cur_token = *p_token;
if (!cf_next_token(cfp)) return false;
if (!cf_token_is(cfp, ".")) return false;
if (!cf_next_token(cfp)) return false;
if (cf_token_is(cfp, "Sample"))
written = gl_write_texture_call(glsp, var, "texture");
else if (cf_token_is(cfp, "SampleBias"))
written = gl_write_texture_call(glsp, var, "texture");
else if (cf_token_is(cfp, "SampleGrad"))
written = gl_write_texture_call(glsp, var, "textureGrad");
else if (cf_token_is(cfp, "SampleLevel"))
written = gl_write_texture_call(glsp, var, "textureLod");
if (!written)
return false;
if (!cf_next_token(cfp)) return false;
gl_write_function_contents(glsp, &cfp->cur_token, ")");
dstr_cat(&glsp->gl_string, ")");
*p_token = cfp->cur_token;
return true;
}
static bool gl_write_intrinsic(struct gl_shader_parser *glsp,
struct cf_token **p_token)
{
struct cf_token *token = *p_token;
bool written = true;
if (strref_cmp(&token->str, "atan2") == 0) {
dstr_cat(&glsp->gl_string, "atan2");
} else if (strref_cmp(&token->str, "ddx") == 0) {
dstr_cat(&glsp->gl_string, "dFdx");
} else if (strref_cmp(&token->str, "ddy") == 0) {
dstr_cat(&glsp->gl_string, "dFdy");
} else if (strref_cmp(&token->str, "frac") == 0) {
dstr_cat(&glsp->gl_string, "fract");
} else if (strref_cmp(&token->str, "lerp") == 0) {
dstr_cat(&glsp->gl_string, "mix");
} else if (strref_cmp(&token->str, "fmod") == 0) {
dstr_cat(&glsp->gl_string, "mod");
} else if (strref_cmp(&token->str, "rsqrt") == 0) {
dstr_cat(&glsp->gl_string, "inversesqrt");
} else if (strref_cmp(&token->str, "saturate") == 0) {
written = gl_write_saturate(glsp, &token);
} else if (strref_cmp(&token->str, "mul") == 0) {
written = gl_write_mul(glsp, &token);
} else {
struct shader_var *var = sp_getparam(glsp, token);
if (var && astrcmp_n(var->type, "texture", 7) == 0)
written = gl_write_texture_code(glsp, &token, var);
else
written = false;
}
if (written)
*p_token = token;
return written;
}
static void gl_write_function_contents(struct gl_shader_parser *glsp,
struct cf_token **p_token, const char *end)
{
struct cf_token *token = *p_token;
if (token->type != CFTOKEN_NAME
|| ( !gl_write_type_token(glsp, token)
&& !gl_write_intrinsic(glsp, &token)))
dstr_cat_strref(&glsp->gl_string, &token->str);
while (token->type != CFTOKEN_NONE) {
token++;
if (end && strref_cmp(&token->str, end) == 0)
break;
if (token->type == CFTOKEN_NAME) {
if (!gl_write_type_token(glsp, token) &&
!gl_write_intrinsic(glsp, &token))
dstr_cat_strref(&glsp->gl_string, &token->str);
} else if (token->type == CFTOKEN_OTHER) {
if (*token->str.array == '{')
gl_write_function_contents(glsp, &token, "}");
else if (*token->str.array == '(')
gl_write_function_contents(glsp, &token, ")");
dstr_cat_strref(&glsp->gl_string, &token->str);
} else {
dstr_cat_strref(&glsp->gl_string, &token->str);
}
}
*p_token = token;
}
static void gl_write_function(struct gl_shader_parser *glsp,
struct shader_func *func)
{
size_t i;
struct cf_token *token;
gl_write_type(glsp, func->return_type);
dstr_cat(&glsp->gl_string, " ");
if (strcmp(func->name, "main") == 0)
dstr_cat(&glsp->gl_string, "_main_wrap");
else
dstr_cat(&glsp->gl_string, func->name);
dstr_cat(&glsp->gl_string, "(");
for (i = 0; i < func->params.num; i++) {
struct shader_var *param = func->params.array+i;
if (i > 0)
dstr_cat(&glsp->gl_string, ", ");
gl_write_var(glsp, param);
}
dstr_cat(&glsp->gl_string, ")\n");
token = func->start;
gl_write_function_contents(glsp, &token, "}");
dstr_cat(&glsp->gl_string, "}\n\n");
}
static inline void gl_write_functions(struct gl_shader_parser *glsp)
{
size_t i;
for (i = 0; i < glsp->parser.funcs.num; i++) {
struct shader_func *func = glsp->parser.funcs.array+i;
gl_write_function(glsp, func);
}
}
static inline void gl_write_main_interface_assign(
struct gl_shader_parser *glsp, struct shader_var *var,
const char *src)
{
/* vertex shaders: write gl_Position */
if (glsp->type == GS_SHADER_VERTEX &&
strcmp(var->mapping, "POSITION") == 0) {
dstr_cat(&glsp->gl_string, "\tgl_Position = ");
dstr_cat(&glsp->gl_string, src);
dstr_cat(&glsp->gl_string, var->name);
dstr_cat(&glsp->gl_string, ";\n");
}
}
static void gl_write_main_storage_assign(struct gl_shader_parser *glsp,
struct shader_var *var, const char *dst, const char *src,
bool input)
{
struct shader_struct *st;
struct dstr dst_copy = {0};
char ch_left = input ? '.' : '_';
char ch_right = input ? '_' : '.';
if (dst) {
dstr_copy(&dst_copy, dst);
dstr_cat_ch(&dst_copy, ch_left);
} else {
dstr_copy(&dst_copy, "\t");
}
dstr_cat(&dst_copy, var->name);
st = shader_parser_getstruct(&glsp->parser, var->type);
if (st) {
struct dstr src_copy = {0};
size_t i;
if (src)
dstr_copy(&src_copy, src);
dstr_cat(&src_copy, var->name);
dstr_cat_ch(&src_copy, ch_right);
for (i = 0; i < st->vars.num; i++) {
struct shader_var *st_var = st->vars.array+i;
gl_write_main_storage_assign(glsp, st_var,
dst_copy.array, src_copy.array, input);
}
dstr_free(&src_copy);
} else {
if (!dstr_is_empty(&dst_copy))
dstr_cat_dstr(&glsp->gl_string, &dst_copy);
dstr_cat(&glsp->gl_string, " = ");
if (src)
dstr_cat(&glsp->gl_string, src);
dstr_cat(&glsp->gl_string, var->name);
dstr_cat(&glsp->gl_string, ";\n");
if (!input)
gl_write_main_interface_assign(glsp, var, src);
}
dstr_free(&dst_copy);
}
static inline void gl_write_main_storage_inputs(struct gl_shader_parser *glsp,
struct shader_func *main)
{
gl_write_main_storage_assign(glsp, main->params.array, NULL,
"inputval_", true);
}
static inline void gl_write_main_storage_outputs(struct gl_shader_parser *glsp,
struct shader_func *main)
{
/* we only do this *if* we're writing a struct, because otherwise
* the call to 'main' already does the assignment for us */
if (!main->mapping) {
struct shader_var var = {0};
var.name = "outputval";
var.type = (char*)main->return_type;
dstr_cat(&glsp->gl_string, "\n");
gl_write_main_storage_assign(glsp, &var, NULL, NULL, false);
}
}
static inline void gl_write_main_vars(struct gl_shader_parser *glsp,
struct shader_func *main_func)
{
size_t i;
for (i = 0; i < main_func->params.num; i++) {
dstr_cat(&glsp->gl_string, "\t");
dstr_cat(&glsp->gl_string, main_func->params.array[i].type);
dstr_cat(&glsp->gl_string, " ");
dstr_cat(&glsp->gl_string, main_func->params.array[i].name);
dstr_cat(&glsp->gl_string, ";\n");
}
if (!main_func->mapping) {
dstr_cat(&glsp->gl_string, "\t");
dstr_cat(&glsp->gl_string, main_func->return_type);
dstr_cat(&glsp->gl_string, " outputval;\n\n");
}
}
static inline void gl_write_main_func_call(struct gl_shader_parser *glsp,
struct shader_func *main_func)
{
size_t i;
dstr_cat(&glsp->gl_string, "\n\toutputval = _main_wrap(");
for (i = 0; i < main_func->params.num; i++) {
if (i)
dstr_cat(&glsp->gl_string, ", ");
dstr_cat(&glsp->gl_string, main_func->params.array[i].name);
}
dstr_cat(&glsp->gl_string, ");\n");
}
static void gl_write_main(struct gl_shader_parser *glsp,
struct shader_func *main)
{
dstr_cat(&glsp->gl_string, "void main(void)\n{\n");
gl_write_main_vars(glsp, main);
gl_write_main_storage_inputs(glsp, main);
gl_write_main_func_call(glsp, main);
gl_write_main_storage_outputs(glsp, main);
dstr_cat(&glsp->gl_string, "}\n");
}
/* ugh, don't ask. I'll probably get rid of the need for this function later */
static void gl_rename_attributes(struct gl_shader_parser *glsp)
{
size_t i = 0, input_idx = 0, output_idx = 0;
for (i = 0; i < glsp->attribs.num; i++) {
struct gl_parser_attrib *attrib = glsp->attribs.array+i;
struct dstr new_name = {0};
const char *prefix;
size_t val;
if (attrib->input) {
prefix = glsp->input_prefix;
val = input_idx++;
} else {
prefix = glsp->output_prefix;
val = output_idx++;
}
dstr_printf(&new_name, "%s%u", prefix, (unsigned int)val);
dstr_replace(&glsp->gl_string, attrib->name.array,
new_name.array);
dstr_move(&attrib->name, &new_name);
}
}
static bool gl_shader_buildstring(struct gl_shader_parser *glsp)
{
struct shader_func *main_func;
main_func = shader_parser_getfunc(&glsp->parser, "main");
if (!main_func) {
blog(LOG_ERROR, "function 'main' not found");
return false;
}
dstr_copy(&glsp->gl_string, "#version 150\n\n");
gl_write_params(glsp);
gl_write_inputs(glsp, main_func);
gl_write_outputs(glsp, main_func);
gl_write_interface_block(glsp);
gl_write_structs(glsp);
gl_write_functions(glsp);
gl_write_main(glsp, main_func);
gl_rename_attributes(glsp);
return true;
}
bool gl_shader_parse(struct gl_shader_parser *glsp,
const char *shader_str, const char *file)
{
bool success = shader_parse(&glsp->parser, shader_str, file);
char *str = shader_parser_geterrors(&glsp->parser);
if (str) {
blog(LOG_WARNING, "Shader parser errors/warnings:\n%s\n", str);
bfree(str);
}
if (success)
success = gl_shader_buildstring(glsp);
return success;
}

View file

@ -0,0 +1,88 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
/*
* Parses shaders into GLSL. Shaders are almost identical to HLSL
* model 5 so it requires quite a bit of tweaking to convert correctly.
* Takes the parsed shader data, and builds a GLSL string out of it.
*/
#include <util/dstr.h>
#include <graphics/shader-parser.h>
struct gl_parser_attrib {
struct dstr name;
const char *mapping;
bool input;
};
static inline void gl_parser_attrib_init(struct gl_parser_attrib *attr)
{
memset(attr, 0, sizeof(struct gl_parser_attrib));
}
static inline void gl_parser_attrib_free(struct gl_parser_attrib *attr)
{
dstr_free(&attr->name);
}
struct gl_shader_parser {
enum gs_shader_type type;
const char *input_prefix;
const char *output_prefix;
struct shader_parser parser;
struct dstr gl_string;
DARRAY(uint32_t) texture_samplers;
DARRAY(struct gl_parser_attrib) attribs;
};
static inline void gl_shader_parser_init(struct gl_shader_parser *glsp,
enum gs_shader_type type)
{
glsp->type = type;
if (type == GS_SHADER_VERTEX) {
glsp->input_prefix = "_input_attrib";
glsp->output_prefix = "_vertex_shader_attrib";
} else if (type == GS_SHADER_PIXEL) {
glsp->input_prefix = "_vertex_shader_attrib";
glsp->output_prefix = "_pixel_shader_attrib";
}
shader_parser_init(&glsp->parser);
dstr_init(&glsp->gl_string);
da_init(glsp->texture_samplers);
da_init(glsp->attribs);
}
static inline void gl_shader_parser_free(struct gl_shader_parser *glsp)
{
size_t i;
for (i = 0; i < glsp->attribs.num; i++)
gl_parser_attrib_free(glsp->attribs.array+i);
da_free(glsp->attribs);
da_free(glsp->texture_samplers);
dstr_free(&glsp->gl_string);
shader_parser_free(&glsp->parser);
}
extern bool gl_shader_parse(struct gl_shader_parser *glsp,
const char *shader_str, const char *file);

View file

@ -0,0 +1,234 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
static bool create_pixel_pack_buffer(struct gs_stage_surface *surf)
{
GLsizeiptr size;
bool success = true;
if (!gl_gen_buffers(1, &surf->pack_buffer))
return false;
if (!gl_bind_buffer(GL_PIXEL_PACK_BUFFER, surf->pack_buffer))
return false;
size = surf->width * surf->bytes_per_pixel;
size = (size+3) & 0xFFFFFFFC; /* align width to 4-byte boundry */
size *= surf->height;
glBufferData(GL_PIXEL_PACK_BUFFER, size, 0, GL_DYNAMIC_READ);
if (!gl_success("glBufferData"))
success = false;
if (!gl_bind_buffer(GL_PIXEL_PACK_BUFFER, 0))
success = false;
return success;
}
gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width,
uint32_t height, enum gs_color_format color_format)
{
struct gs_stage_surface *surf;
surf = bzalloc(sizeof(struct gs_stage_surface));
surf->device = device;
surf->format = color_format;
surf->width = width;
surf->height = height;
surf->gl_format = convert_gs_format(color_format);
surf->gl_internal_format = convert_gs_internal_format(color_format);
surf->gl_type = get_gl_format_type(color_format);
surf->bytes_per_pixel = gs_get_format_bpp(color_format)/8;
if (!create_pixel_pack_buffer(surf)) {
blog(LOG_ERROR, "device_stagesurface_create (GL) failed");
gs_stagesurface_destroy(surf);
return NULL;
}
return surf;
}
void gs_stagesurface_destroy(gs_stagesurf_t *stagesurf)
{
if (stagesurf) {
if (stagesurf->pack_buffer)
gl_delete_buffers(1, &stagesurf->pack_buffer);
bfree(stagesurf);
}
}
static bool can_stage(struct gs_stage_surface *dst, struct gs_texture_2d *src)
{
if (!src) {
blog(LOG_ERROR, "Source texture is NULL");
return false;
}
if (src->base.type != GS_TEXTURE_2D) {
blog(LOG_ERROR, "Source texture must be a 2D texture");
return false;
}
if (!dst) {
blog(LOG_ERROR, "Destination surface is NULL");
return false;
}
if (src->base.format != dst->format) {
blog(LOG_ERROR, "Source and destination formats do not match");
return false;
}
if (src->width != dst->width || src->height != dst->height) {
blog(LOG_ERROR, "Source and destination must have the same "
"dimensions");
return false;
}
return true;
}
#ifdef __APPLE__
/* Apparently for mac, PBOs won't do an asynchronous transfer unless you use
* FBOs aong with glReadPixels, which is really dumb. */
void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst,
gs_texture_t *src)
{
struct gs_texture_2d *tex2d = (struct gs_texture_2d*)src;
struct fbo_info *fbo;
GLint last_fbo;
bool success = false;
if (!can_stage(dst, tex2d))
goto failed;
if (!gl_bind_buffer(GL_PIXEL_PACK_BUFFER, dst->pack_buffer))
goto failed;
fbo = get_fbo(device, dst->width, dst->height, dst->format);
if (!gl_get_integer_v(GL_READ_FRAMEBUFFER_BINDING, &last_fbo))
goto failed_unbind_buffer;
if (!gl_bind_framebuffer(GL_READ_FRAMEBUFFER, fbo->fbo))
goto failed_unbind_buffer;
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0,
src->gl_target, src->texture, 0);
if (!gl_success("glFrameBufferTexture2D"))
goto failed_unbind_all;
glReadPixels(0, 0, dst->width, dst->height, dst->gl_format,
dst->gl_type, 0);
if (!gl_success("glReadPixels"))
goto failed_unbind_all;
success = true;
failed_unbind_all:
gl_bind_framebuffer(GL_READ_FRAMEBUFFER, last_fbo);
failed_unbind_buffer:
gl_bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
failed:
if (!success)
blog(LOG_ERROR, "device_stage_texture (GL) failed");
}
#else
void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst,
gs_texture_t *src)
{
struct gs_texture_2d *tex2d = (struct gs_texture_2d*)src;
if (!can_stage(dst, tex2d))
goto failed;
if (!gl_bind_buffer(GL_PIXEL_PACK_BUFFER, dst->pack_buffer))
goto failed;
if (!gl_bind_texture(GL_TEXTURE_2D, tex2d->base.texture))
goto failed;
glGetTexImage(GL_TEXTURE_2D, 0, dst->gl_format, dst->gl_type, 0);
if (!gl_success("glGetTexImage"))
goto failed;
gl_bind_texture(GL_TEXTURE_2D, 0);
gl_bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
return;
failed:
gl_bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
gl_bind_texture(GL_TEXTURE_2D, 0);
blog(LOG_ERROR, "device_stage_texture (GL) failed");
UNUSED_PARAMETER(device);
}
#endif
uint32_t gs_stagesurface_get_width(const gs_stagesurf_t *stagesurf)
{
return stagesurf->width;
}
uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf)
{
return stagesurf->height;
}
enum gs_color_format gs_stagesurface_get_color_format(
const gs_stagesurf_t *stagesurf)
{
return stagesurf->format;
}
bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data,
uint32_t *linesize)
{
if (!gl_bind_buffer(GL_PIXEL_PACK_BUFFER, stagesurf->pack_buffer))
goto fail;
*data = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
if (!gl_success("glMapBuffer"))
goto fail;
gl_bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
*linesize = stagesurf->bytes_per_pixel * stagesurf->width;
return true;
fail:
blog(LOG_ERROR, "stagesurf_map (GL) failed");
return false;
}
void gs_stagesurface_unmap(gs_stagesurf_t *stagesurf)
{
if (!gl_bind_buffer(GL_PIXEL_PACK_BUFFER, stagesurf->pack_buffer))
return;
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
gl_success("glUnmapBuffer");
gl_bind_buffer(GL_PIXEL_PACK_BUFFER, 0);
}

1388
libobs-opengl/gl-subsystem.c Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,525 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#pragma once
#include <util/darray.h>
#include <util/threading.h>
#include <graphics/graphics.h>
#include <graphics/device-exports.h>
#include <graphics/matrix4.h>
#include <glad/glad.h>
#include "gl-helpers.h"
struct gl_platform;
struct gl_windowinfo;
enum copy_type {
COPY_TYPE_ARB,
COPY_TYPE_NV,
COPY_TYPE_FBO_BLIT
};
static inline GLint convert_gs_format(enum gs_color_format format)
{
switch (format) {
case GS_A8: return GL_RGBA;
case GS_R8: return GL_RED;
case GS_RGBA: return GL_RGBA;
case GS_BGRX: return GL_BGRA;
case GS_BGRA: return GL_BGRA;
case GS_R10G10B10A2: return GL_RGBA;
case GS_RGBA16: return GL_RGBA;
case GS_R16: return GL_RED;
case GS_RGBA16F: return GL_RGBA;
case GS_RGBA32F: return GL_RGBA;
case GS_RG16F: return GL_RG;
case GS_RG32F: return GL_RG;
case GS_R16F: return GL_RED;
case GS_R32F: return GL_RED;
case GS_DXT1: return GL_RGB;
case GS_DXT3: return GL_RGBA;
case GS_DXT5: return GL_RGBA;
case GS_UNKNOWN: return 0;
}
return 0;
}
static inline GLint convert_gs_internal_format(enum gs_color_format format)
{
switch (format) {
case GS_A8: return GL_R8; /* NOTE: use GL_TEXTURE_SWIZZLE_x */
case GS_R8: return GL_R8;
case GS_RGBA: return GL_RGBA;
case GS_BGRX: return GL_RGB;
case GS_BGRA: return GL_RGBA;
case GS_R10G10B10A2: return GL_RGB10_A2;
case GS_RGBA16: return GL_RGBA16;
case GS_R16: return GL_R16;
case GS_RGBA16F: return GL_RGBA16F;
case GS_RGBA32F: return GL_RGBA32F;
case GS_RG16F: return GL_RG16F;
case GS_RG32F: return GL_RG32F;
case GS_R16F: return GL_R16F;
case GS_R32F: return GL_R32F;
case GS_DXT1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case GS_DXT3: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
case GS_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case GS_UNKNOWN: return 0;
}
return 0;
}
static inline GLenum get_gl_format_type(enum gs_color_format format)
{
switch (format) {
case GS_A8: return GL_UNSIGNED_BYTE;
case GS_R8: return GL_UNSIGNED_BYTE;
case GS_RGBA: return GL_UNSIGNED_BYTE;
case GS_BGRX: return GL_UNSIGNED_BYTE;
case GS_BGRA: return GL_UNSIGNED_BYTE;
case GS_R10G10B10A2: return GL_UNSIGNED_INT_10_10_10_2;
case GS_RGBA16: return GL_UNSIGNED_SHORT;
case GS_R16: return GL_UNSIGNED_SHORT;
case GS_RGBA16F: return GL_UNSIGNED_SHORT;
case GS_RGBA32F: return GL_FLOAT;
case GS_RG16F: return GL_UNSIGNED_SHORT;
case GS_RG32F: return GL_FLOAT;
case GS_R16F: return GL_UNSIGNED_SHORT;
case GS_R32F: return GL_FLOAT;
case GS_DXT1: return GL_UNSIGNED_BYTE;
case GS_DXT3: return GL_UNSIGNED_BYTE;
case GS_DXT5: return GL_UNSIGNED_BYTE;
case GS_UNKNOWN: return 0;
}
return GL_UNSIGNED_BYTE;
}
static inline GLenum convert_zstencil_format(enum gs_zstencil_format format)
{
switch (format) {
case GS_Z16: return GL_DEPTH_COMPONENT16;
case GS_Z24_S8: return GL_DEPTH24_STENCIL8;
case GS_Z32F: return GL_DEPTH_COMPONENT32F;
case GS_Z32F_S8X24: return GL_DEPTH32F_STENCIL8;
case GS_ZS_NONE: return 0;
}
return 0;
}
static inline GLenum convert_gs_depth_test(enum gs_depth_test test)
{
switch (test) {
case GS_NEVER: return GL_NEVER;
case GS_LESS: return GL_LESS;
case GS_LEQUAL: return GL_LEQUAL;
case GS_EQUAL: return GL_EQUAL;
case GS_GEQUAL: return GL_GEQUAL;
case GS_GREATER: return GL_GREATER;
case GS_NOTEQUAL: return GL_NOTEQUAL;
case GS_ALWAYS: return GL_ALWAYS;
}
return GL_NEVER;
}
static inline GLenum convert_gs_stencil_op(enum gs_stencil_op_type op)
{
switch (op) {
case GS_KEEP: return GL_KEEP;
case GS_ZERO: return GL_ZERO;
case GS_REPLACE: return GL_REPLACE;
case GS_INCR: return GL_INCR;
case GS_DECR: return GL_DECR;
case GS_INVERT: return GL_INVERT;
}
return GL_KEEP;
}
static inline GLenum convert_gs_stencil_side(enum gs_stencil_side side)
{
switch (side) {
case GS_STENCIL_FRONT: return GL_FRONT;
case GS_STENCIL_BACK: return GL_BACK;
case GS_STENCIL_BOTH: return GL_FRONT_AND_BACK;
}
return GL_FRONT;
}
static inline GLenum convert_gs_blend_type(enum gs_blend_type type)
{
switch (type) {
case GS_BLEND_ZERO: return GL_ZERO;
case GS_BLEND_ONE: return GL_ONE;
case GS_BLEND_SRCCOLOR: return GL_SRC_COLOR;
case GS_BLEND_INVSRCCOLOR: return GL_ONE_MINUS_SRC_COLOR;
case GS_BLEND_SRCALPHA: return GL_SRC_ALPHA;
case GS_BLEND_INVSRCALPHA: return GL_ONE_MINUS_SRC_ALPHA;
case GS_BLEND_DSTCOLOR: return GL_DST_COLOR;
case GS_BLEND_INVDSTCOLOR: return GL_ONE_MINUS_DST_COLOR;
case GS_BLEND_DSTALPHA: return GL_DST_ALPHA;
case GS_BLEND_INVDSTALPHA: return GL_ONE_MINUS_DST_ALPHA;
case GS_BLEND_SRCALPHASAT: return GL_SRC_ALPHA_SATURATE;
}
return GL_ONE;
}
static inline GLenum convert_shader_type(enum gs_shader_type type)
{
switch (type) {
case GS_SHADER_VERTEX: return GL_VERTEX_SHADER;
case GS_SHADER_PIXEL: return GL_FRAGMENT_SHADER;
}
return GL_VERTEX_SHADER;
}
static inline void convert_filter(enum gs_sample_filter filter,
GLint *min_filter, GLint *mag_filter)
{
switch (filter) {
case GS_FILTER_POINT:
*min_filter = GL_NEAREST_MIPMAP_NEAREST;
*mag_filter = GL_NEAREST;
return;
case GS_FILTER_LINEAR:
*min_filter = GL_LINEAR_MIPMAP_LINEAR;
*mag_filter = GL_LINEAR;
return;
case GS_FILTER_MIN_MAG_POINT_MIP_LINEAR:
*min_filter = GL_NEAREST_MIPMAP_LINEAR;
*mag_filter = GL_NEAREST;
return;
case GS_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT:
*min_filter = GL_NEAREST_MIPMAP_NEAREST;
*mag_filter = GL_LINEAR;
return;
case GS_FILTER_MIN_POINT_MAG_MIP_LINEAR:
*min_filter = GL_NEAREST_MIPMAP_LINEAR;
*mag_filter = GL_LINEAR;
return;
case GS_FILTER_MIN_LINEAR_MAG_MIP_POINT:
*min_filter = GL_LINEAR_MIPMAP_NEAREST;
*mag_filter = GL_NEAREST;
return;
case GS_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR:
*min_filter = GL_LINEAR_MIPMAP_LINEAR;
*mag_filter = GL_NEAREST;
return;
case GS_FILTER_MIN_MAG_LINEAR_MIP_POINT:
*min_filter = GL_LINEAR_MIPMAP_NEAREST;
*mag_filter = GL_LINEAR;
return;
case GS_FILTER_ANISOTROPIC:
*min_filter = GL_LINEAR_MIPMAP_LINEAR;
*mag_filter = GL_LINEAR;
return;
}
*min_filter = GL_NEAREST_MIPMAP_NEAREST;
*mag_filter = GL_NEAREST;
}
static inline GLint convert_address_mode(enum gs_address_mode mode)
{
switch (mode) {
case GS_ADDRESS_WRAP: return GL_REPEAT;
case GS_ADDRESS_CLAMP: return GL_CLAMP_TO_EDGE;
case GS_ADDRESS_MIRROR: return GL_MIRRORED_REPEAT;
case GS_ADDRESS_BORDER: return GL_CLAMP_TO_BORDER;
case GS_ADDRESS_MIRRORONCE: return GL_MIRROR_CLAMP_EXT;
}
return GL_REPEAT;
}
static inline GLenum convert_gs_topology(enum gs_draw_mode mode)
{
switch (mode) {
case GS_POINTS: return GL_POINTS;
case GS_LINES: return GL_LINES;
case GS_LINESTRIP: return GL_LINE_STRIP;
case GS_TRIS: return GL_TRIANGLES;
case GS_TRISTRIP: return GL_TRIANGLE_STRIP;
}
return GL_POINTS;
}
extern void convert_sampler_info(struct gs_sampler_state *sampler,
const struct gs_sampler_info *info);
struct gs_sampler_state {
gs_device_t *device;
volatile long ref;
GLint min_filter;
GLint mag_filter;
GLint address_u;
GLint address_v;
GLint address_w;
GLint max_anisotropy;
};
static inline void samplerstate_addref(gs_samplerstate_t *ss)
{
os_atomic_inc_long(&ss->ref);
}
static inline void samplerstate_release(gs_samplerstate_t *ss)
{
if (os_atomic_dec_long(&ss->ref) == 0)
bfree(ss);
}
struct gs_shader_param {
enum gs_shader_param_type type;
char *name;
gs_shader_t *shader;
GLint texture_id;
size_t sampler_id;
int array_count;
struct gs_texture *texture;
DARRAY(uint8_t) cur_value;
DARRAY(uint8_t) def_value;
bool changed;
};
enum attrib_type {
ATTRIB_POSITION,
ATTRIB_NORMAL,
ATTRIB_TANGENT,
ATTRIB_COLOR,
ATTRIB_TEXCOORD,
ATTRIB_TARGET
};
struct shader_attrib {
char *name;
size_t index;
enum attrib_type type;
};
struct gs_shader {
gs_device_t *device;
enum gs_shader_type type;
GLuint obj;
struct gs_shader_param *viewproj;
struct gs_shader_param *world;
DARRAY(struct shader_attrib) attribs;
DARRAY(struct gs_shader_param) params;
DARRAY(gs_samplerstate_t*) samplers;
};
struct program_param {
GLint obj;
struct gs_shader_param *param;
};
struct gs_program {
gs_device_t *device;
GLuint obj;
struct gs_shader *vertex_shader;
struct gs_shader *pixel_shader;
DARRAY(struct program_param) params;
DARRAY(GLint) attribs;
struct gs_program **prev_next;
struct gs_program *next;
};
extern struct gs_program *gs_program_create(struct gs_device *device);
extern void gs_program_destroy(struct gs_program *program);
extern void program_update_params(struct gs_program *shader);
struct gs_vertex_buffer {
GLuint vao;
GLuint vertex_buffer;
GLuint normal_buffer;
GLuint tangent_buffer;
GLuint color_buffer;
DARRAY(GLuint) uv_buffers;
DARRAY(size_t) uv_sizes;
gs_device_t *device;
size_t num;
bool dynamic;
struct gs_vb_data *data;
};
extern bool load_vb_buffers(struct gs_program *program,
struct gs_vertex_buffer *vb);
struct gs_index_buffer {
GLuint buffer;
enum gs_index_type type;
GLuint gl_type;
gs_device_t *device;
void *data;
size_t num;
size_t width;
size_t size;
bool dynamic;
};
struct gs_texture {
gs_device_t *device;
enum gs_texture_type type;
enum gs_color_format format;
GLenum gl_format;
GLenum gl_target;
GLint gl_internal_format;
GLenum gl_type;
GLuint texture;
uint32_t levels;
bool is_dynamic;
bool is_render_target;
bool is_dummy;
bool gen_mipmaps;
gs_samplerstate_t *cur_sampler;
};
struct gs_texture_2d {
struct gs_texture base;
uint32_t width;
uint32_t height;
bool gen_mipmaps;
GLuint unpack_buffer;
};
struct gs_texture_cube {
struct gs_texture base;
uint32_t size;
};
struct gs_stage_surface {
gs_device_t *device;
enum gs_color_format format;
uint32_t width;
uint32_t height;
uint32_t bytes_per_pixel;
GLenum gl_format;
GLint gl_internal_format;
GLenum gl_type;
GLuint pack_buffer;
};
struct gs_zstencil_buffer {
gs_device_t *device;
GLuint buffer;
GLuint attachment;
GLenum format;
};
struct gs_swap_chain {
gs_device_t *device;
struct gl_windowinfo *wi;
struct gs_init_data info;
};
struct fbo_info {
GLuint fbo;
uint32_t width;
uint32_t height;
enum gs_color_format format;
gs_texture_t *cur_render_target;
int cur_render_side;
gs_zstencil_t *cur_zstencil_buffer;
};
static inline void fbo_info_destroy(struct fbo_info *fbo)
{
if (fbo) {
glDeleteFramebuffers(1, &fbo->fbo);
gl_success("glDeleteFramebuffers");
bfree(fbo);
}
}
struct gs_device {
struct gl_platform *plat;
enum copy_type copy_type;
gs_texture_t *cur_render_target;
gs_zstencil_t *cur_zstencil_buffer;
int cur_render_side;
gs_texture_t *cur_textures[GS_MAX_TEXTURES];
gs_samplerstate_t *cur_samplers[GS_MAX_TEXTURES];
gs_vertbuffer_t *cur_vertex_buffer;
gs_indexbuffer_t *cur_index_buffer;
gs_shader_t *cur_vertex_shader;
gs_shader_t *cur_pixel_shader;
gs_swapchain_t *cur_swap;
struct gs_program *cur_program;
struct gs_program *first_program;
enum gs_cull_mode cur_cull_mode;
struct gs_rect cur_viewport;
struct matrix4 cur_proj;
struct matrix4 cur_view;
struct matrix4 cur_viewproj;
DARRAY(struct matrix4) proj_stack;
DARRAY(struct fbo_info*) fbos;
struct fbo_info *cur_fbo;
};
extern struct fbo_info *get_fbo(struct gs_device *device,
uint32_t width, uint32_t height, enum gs_color_format format);
extern void gl_update(gs_device_t *device);
extern struct gl_platform *gl_platform_create(gs_device_t *device,
uint32_t adapter);
extern void gl_platform_destroy(struct gl_platform *platform);
extern bool gl_platform_init_swapchain(struct gs_swap_chain *swap);
extern void gl_platform_cleanup_swapchain(struct gs_swap_chain *swap);
extern struct gl_windowinfo *gl_windowinfo_create(
const struct gs_init_data *info);
extern void gl_windowinfo_destroy(struct gl_windowinfo *wi);
extern void gl_getclientsize(const struct gs_swap_chain *swap,
uint32_t *width,
uint32_t *height);

View file

@ -0,0 +1,249 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
static bool upload_texture_2d(struct gs_texture_2d *tex, const uint8_t **data)
{
uint32_t row_size = tex->width * gs_get_format_bpp(tex->base.format);
uint32_t tex_size = tex->height * row_size / 8;
uint32_t num_levels = tex->base.levels;
bool compressed = gs_is_compressed_format(tex->base.format);
bool success;
if (!num_levels)
num_levels = gs_get_total_levels(tex->width, tex->height);
if (!gl_bind_texture(GL_TEXTURE_2D, tex->base.texture))
return false;
success = gl_init_face(GL_TEXTURE_2D, tex->base.gl_type, num_levels,
tex->base.gl_format, tex->base.gl_internal_format,
compressed, tex->width, tex->height, tex_size, &data);
if (!gl_tex_param_i(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, num_levels-1))
success = false;
if (!gl_bind_texture(GL_TEXTURE_2D, 0))
success = false;
return success;
}
static bool create_pixel_unpack_buffer(struct gs_texture_2d *tex)
{
GLsizeiptr size;
bool success = true;
if (!gl_gen_buffers(1, &tex->unpack_buffer))
return false;
if (!gl_bind_buffer(GL_PIXEL_UNPACK_BUFFER, tex->unpack_buffer))
return false;
size = tex->width * gs_get_format_bpp(tex->base.format);
if (!gs_is_compressed_format(tex->base.format)) {
size /= 8;
size = (size+3) & 0xFFFFFFFC;
size *= tex->height;
} else {
size *= tex->height;
size /= 8;
}
glBufferData(GL_PIXEL_UNPACK_BUFFER, size, 0, GL_DYNAMIC_DRAW);
if (!gl_success("glBufferData"))
success = false;
if (!gl_bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0))
success = false;
return success;
}
gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width,
uint32_t height, enum gs_color_format color_format,
uint32_t levels, const uint8_t **data, uint32_t flags)
{
struct gs_texture_2d *tex = bzalloc(sizeof(struct gs_texture_2d));
tex->base.device = device;
tex->base.type = GS_TEXTURE_2D;
tex->base.format = color_format;
tex->base.levels = levels;
tex->base.gl_format = convert_gs_format(color_format);
tex->base.gl_internal_format = convert_gs_internal_format(color_format);
tex->base.gl_type = get_gl_format_type(color_format);
tex->base.gl_target = GL_TEXTURE_2D;
tex->base.is_dynamic = (flags & GS_DYNAMIC) != 0;
tex->base.is_render_target = (flags & GS_RENDER_TARGET) != 0;
tex->base.is_dummy = (flags & GS_GL_DUMMYTEX) != 0;
tex->base.gen_mipmaps = (flags & GS_BUILD_MIPMAPS) != 0;
tex->width = width;
tex->height = height;
if (!gl_gen_textures(1, &tex->base.texture))
goto fail;
if (!tex->base.is_dummy) {
if (tex->base.is_dynamic && !create_pixel_unpack_buffer(tex))
goto fail;
if (!upload_texture_2d(tex, data))
goto fail;
}
return (gs_texture_t*)tex;
fail:
gs_texture_destroy((gs_texture_t*)tex);
blog(LOG_ERROR, "device_texture_create (GL) failed");
return NULL;
}
static inline bool is_texture_2d(const gs_texture_t *tex, const char *func)
{
bool is_tex2d = tex->type == GS_TEXTURE_2D;
if (!is_tex2d)
blog(LOG_ERROR, "%s (GL) failed: Not a 2D texture", func);
return is_tex2d;
}
void gs_texture_destroy(gs_texture_t *tex)
{
struct gs_texture_2d *tex2d = (struct gs_texture_2d*)tex;
if (!tex)
return;
if (!is_texture_2d(tex, "gs_texture_destroy"))
return;
if (tex->cur_sampler)
gs_samplerstate_destroy(tex->cur_sampler);
if (!tex->is_dummy && tex->is_dynamic && tex2d->unpack_buffer)
gl_delete_buffers(1, &tex2d->unpack_buffer);
if (tex->texture)
gl_delete_textures(1, &tex->texture);
bfree(tex);
}
uint32_t gs_texture_get_width(const gs_texture_t *tex)
{
const struct gs_texture_2d *tex2d = (const struct gs_texture_2d*)tex;
if (!is_texture_2d(tex, "gs_texture_get_width"))
return 0;
return tex2d->width;
}
uint32_t gs_texture_get_height(const gs_texture_t *tex)
{
const struct gs_texture_2d *tex2d = (const struct gs_texture_2d*)tex;
if (!is_texture_2d(tex, "gs_texture_get_height"))
return 0;
return tex2d->height;
}
enum gs_color_format gs_texture_get_color_format(const gs_texture_t *tex)
{
return tex->format;
}
bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize)
{
struct gs_texture_2d *tex2d = (struct gs_texture_2d*)tex;
if (!is_texture_2d(tex, "gs_texture_map"))
goto fail;
if (!tex2d->base.is_dynamic) {
blog(LOG_ERROR, "Texture is not dynamic");
goto fail;
}
if (!gl_bind_buffer(GL_PIXEL_UNPACK_BUFFER, tex2d->unpack_buffer))
goto fail;
*ptr = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
if (!gl_success("glMapBuffer"))
goto fail;
gl_bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);
*linesize = tex2d->width * gs_get_format_bpp(tex->format) / 8;
*linesize = (*linesize + 3) & 0xFFFFFFFC;
return true;
fail:
blog(LOG_ERROR, "gs_texture_map (GL) failed");
return false;
}
void gs_texture_unmap(gs_texture_t *tex)
{
struct gs_texture_2d *tex2d = (struct gs_texture_2d*)tex;
if (!is_texture_2d(tex, "gs_texture_unmap"))
goto failed;
if (!gl_bind_buffer(GL_PIXEL_UNPACK_BUFFER, tex2d->unpack_buffer))
goto failed;
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
if (!gl_success("glUnmapBuffer"))
goto failed;
if (!gl_bind_texture(GL_TEXTURE_2D, tex2d->base.texture))
goto failed;
glTexImage2D(GL_TEXTURE_2D, 0, tex->gl_internal_format,
tex2d->width, tex2d->height, 0,
tex->gl_format, tex->gl_type, 0);
if (!gl_success("glTexImage2D"))
goto failed;
gl_bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);
gl_bind_texture(GL_TEXTURE_2D, 0);
return;
failed:
gl_bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);
gl_bind_texture(GL_TEXTURE_2D, 0);
blog(LOG_ERROR, "gs_texture_unmap (GL) failed");
}
bool gs_texture_is_rect(const gs_texture_t *tex)
{
const struct gs_texture_2d *tex2d = (const struct gs_texture_2d*)tex;
if (!is_texture_2d(tex, "gs_texture_unmap")) {
blog(LOG_ERROR, "gs_texture_is_rect (GL) failed");
return false;
}
return tex2d->base.gl_target == GL_TEXTURE_RECTANGLE;
}
void *gs_texture_get_obj(gs_texture_t *tex)
{
struct gs_texture_2d *tex2d = (struct gs_texture_2d*)tex;
if (!is_texture_2d(tex, "gs_texture_unmap")) {
blog(LOG_ERROR, "gs_texture_get_obj (GL) failed");
return NULL;
}
return &tex2d->base.texture;
}

View file

@ -0,0 +1,126 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
static inline bool upload_texture_cube(struct gs_texture_cube *tex,
const uint8_t **data)
{
uint32_t row_size = tex->size * gs_get_format_bpp(tex->base.format);
uint32_t tex_size = tex->size * row_size / 8;
uint32_t num_levels = tex->base.levels;
bool compressed = gs_is_compressed_format(tex->base.format);
GLenum gl_type = get_gl_format_type(tex->base.format);
bool success = true;
uint32_t i;
if (!num_levels)
num_levels = gs_get_total_levels(tex->size, tex->size);
for (i = 0; i < 6; i++) {
GLenum target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + i;
if (!gl_bind_texture(target, tex->base.texture))
success = false;
if (!gl_init_face(target, gl_type, num_levels,
tex->base.gl_format,
tex->base.gl_internal_format,
compressed, tex->size, tex->size,
tex_size, &data))
success = false;
if (!gl_bind_texture(target, 0))
success = false;
if (data)
data++;
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, num_levels);
if (!gl_success("glTexParameteri"))
success = false;
return success;
}
gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size,
enum gs_color_format color_format, uint32_t levels,
const uint8_t **data, uint32_t flags)
{
struct gs_texture_cube *tex = bzalloc(sizeof(struct gs_texture_cube));
tex->base.device = device;
tex->base.type = GS_TEXTURE_CUBE;
tex->base.format = color_format;
tex->base.levels = levels;
tex->base.gl_format = convert_gs_format(color_format);
tex->base.gl_internal_format = convert_gs_internal_format(color_format);
tex->base.gl_target = GL_TEXTURE_CUBE_MAP;
tex->base.is_render_target = (flags & GS_RENDER_TARGET) != 0;
tex->base.gen_mipmaps = (flags & GS_BUILD_MIPMAPS) != 0;
tex->size = size;
if (!gl_gen_textures(1, &tex->base.texture))
goto fail;
if (!upload_texture_cube(tex, data))
goto fail;
return (gs_texture_t*)tex;
fail:
gs_cubetexture_destroy((gs_texture_t*)tex);
blog(LOG_ERROR, "device_cubetexture_create (GL) failed");
return NULL;
}
void gs_cubetexture_destroy(gs_texture_t *tex)
{
if (!tex)
return;
if (tex->texture) {
glDeleteTextures(1, &tex->texture);
gl_success("glDeleteTextures");
}
bfree(tex);
}
static inline bool is_texture_cube(const gs_texture_t *tex, const char *func)
{
bool is_texcube = tex->type == GS_TEXTURE_CUBE;
if (!is_texcube)
blog(LOG_ERROR, "%s (GL) failed: Not a cubemap texture", func);
return is_texcube;
}
uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex)
{
const struct gs_texture_cube *cube =
(const struct gs_texture_cube*)cubetex;
if (!is_texture_cube(cubetex, "gs_cubetexture_get_size"))
return 0;
return cube->size;
}
enum gs_color_format gs_cubetexture_get_color_format(
const gs_texture_t *cubetex)
{
return cubetex->format;
}

View file

@ -0,0 +1,257 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <graphics/vec3.h>
#include "gl-subsystem.h"
static bool create_buffers(struct gs_vertex_buffer *vb)
{
GLenum usage = vb->dynamic ? GL_STREAM_DRAW : GL_STATIC_DRAW;
size_t i;
if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->vertex_buffer,
vb->data->num * sizeof(struct vec3),
vb->data->points, usage))
return false;
if (vb->data->normals) {
if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->normal_buffer,
vb->data->num * sizeof(struct vec3),
vb->data->normals, usage))
return false;
}
if (vb->data->tangents) {
if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->tangent_buffer,
vb->data->num * sizeof(struct vec3),
vb->data->tangents, usage))
return false;
}
if (vb->data->colors) {
if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->color_buffer,
vb->data->num * sizeof(uint32_t),
vb->data->colors, usage))
return false;
}
da_reserve(vb->uv_buffers, vb->data->num_tex);
da_reserve(vb->uv_sizes, vb->data->num_tex);
for (i = 0; i < vb->data->num_tex; i++) {
GLuint tex_buffer;
struct gs_tvertarray *tv = vb->data->tvarray+i;
size_t size = vb->data->num * sizeof(float) * tv->width;
if (!gl_create_buffer(GL_ARRAY_BUFFER, &tex_buffer, size,
tv->array, usage))
return false;
da_push_back(vb->uv_buffers, &tex_buffer);
da_push_back(vb->uv_sizes, &tv->width);
}
if (!vb->dynamic) {
gs_vbdata_destroy(vb->data);
vb->data = NULL;
}
if (!gl_gen_vertex_arrays(1, &vb->vao))
return false;
return true;
}
gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device,
struct gs_vb_data *data, uint32_t flags)
{
struct gs_vertex_buffer *vb = bzalloc(sizeof(struct gs_vertex_buffer));
vb->device = device;
vb->data = data;
vb->num = data->num;
vb->dynamic = flags & GS_DYNAMIC;
if (!create_buffers(vb)) {
blog(LOG_ERROR, "device_vertexbuffer_create (GL) failed");
gs_vertexbuffer_destroy(vb);
return NULL;
}
return vb;
}
void gs_vertexbuffer_destroy(gs_vertbuffer_t *vb)
{
if (vb) {
if (vb->vertex_buffer)
gl_delete_buffers(1, &vb->vertex_buffer);
if (vb->normal_buffer)
gl_delete_buffers(1, &vb->normal_buffer);
if (vb->tangent_buffer)
gl_delete_buffers(1, &vb->tangent_buffer);
if (vb->color_buffer)
gl_delete_buffers(1, &vb->color_buffer);
if (vb->uv_buffers.num)
gl_delete_buffers((GLsizei)vb->uv_buffers.num,
vb->uv_buffers.array);
if (vb->vao)
gl_delete_vertex_arrays(1, &vb->vao);
da_free(vb->uv_sizes);
da_free(vb->uv_buffers);
gs_vbdata_destroy(vb->data);
bfree(vb);
}
}
void gs_vertexbuffer_flush(gs_vertbuffer_t *vb)
{
size_t i;
if (!vb->dynamic) {
blog(LOG_ERROR, "vertex buffer is not dynamic");
goto failed;
}
if (!update_buffer(GL_ARRAY_BUFFER, vb->vertex_buffer,
vb->data->points,
vb->data->num * sizeof(struct vec3)))
goto failed;
if (vb->normal_buffer) {
if (!update_buffer(GL_ARRAY_BUFFER, vb->normal_buffer,
vb->data->normals,
vb->data->num * sizeof(struct vec3)))
goto failed;
}
if (vb->tangent_buffer) {
if (!update_buffer(GL_ARRAY_BUFFER, vb->tangent_buffer,
vb->data->tangents,
vb->data->num * sizeof(struct vec3)))
goto failed;
}
if (vb->color_buffer) {
if (!update_buffer(GL_ARRAY_BUFFER, vb->color_buffer,
vb->data->colors,
vb->data->num * sizeof(uint32_t)))
goto failed;
}
for (i = 0; i < vb->data->num_tex; i++) {
GLuint buffer = vb->uv_buffers.array[i];
struct gs_tvertarray *tv = vb->data->tvarray+i;
size_t size = vb->data->num * tv->width * sizeof(float);
if (!update_buffer(GL_ARRAY_BUFFER, buffer, tv->array, size))
goto failed;
}
return;
failed:
blog(LOG_ERROR, "gs_vertexbuffer_flush (GL) failed");
}
struct gs_vb_data *gs_vertexbuffer_get_data(const gs_vertbuffer_t *vb)
{
return vb->data;
}
static inline GLuint get_vb_buffer(struct gs_vertex_buffer *vb,
enum attrib_type type, size_t index, GLint *width,
GLenum *gl_type)
{
*gl_type = GL_FLOAT;
*width = 4;
if (type == ATTRIB_POSITION) {
return vb->vertex_buffer;
} else if (type == ATTRIB_NORMAL) {
return vb->normal_buffer;
} else if (type == ATTRIB_TANGENT) {
return vb->tangent_buffer;
} else if (type == ATTRIB_COLOR) {
*gl_type = GL_UNSIGNED_BYTE;
return vb->color_buffer;
} else if (type == ATTRIB_TEXCOORD) {
if (vb->uv_buffers.num <= index)
return 0;
*width = (GLint)vb->uv_sizes.array[index];
return vb->uv_buffers.array[index];
}
return 0;
}
static bool load_vb_buffer(struct shader_attrib *attrib,
struct gs_vertex_buffer *vb, GLint id)
{
GLenum type;
GLint width;
GLuint buffer;
bool success = true;
buffer = get_vb_buffer(vb, attrib->type, attrib->index, &width, &type);
if (!buffer) {
blog(LOG_ERROR, "Vertex buffer does not have the required "
"inputs for vertex shader");
return false;
}
if (!gl_bind_buffer(GL_ARRAY_BUFFER, buffer))
return false;
glVertexAttribPointer(id, width, type, GL_TRUE, 0, 0);
if (!gl_success("glVertexAttribPointer"))
success = false;
glEnableVertexAttribArray(id);
if (!gl_success("glEnableVertexAttribArray"))
success = false;
if (!gl_bind_buffer(GL_ARRAY_BUFFER, 0))
success = false;
return success;
}
bool load_vb_buffers(struct gs_program *program, struct gs_vertex_buffer *vb)
{
struct gs_shader *shader = program->vertex_shader;
size_t i;
if (!gl_bind_vertex_array(vb->vao))
return false;
for (i = 0; i < shader->attribs.num; i++) {
struct shader_attrib *attrib = shader->attribs.array+i;
if (!load_vb_buffer(attrib, vb, program->attribs.array[i]))
return false;
}
return true;
}
void device_load_vertexbuffer(gs_device_t *device, gs_vertbuffer_t *vb)
{
device->cur_vertex_buffer = vb;
}

592
libobs-opengl/gl-windows.c Normal file
View file

@ -0,0 +1,592 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <util/darray.h>
#include "gl-subsystem.h"
#include <glad/glad_wgl.h>
/* Basically swapchain-specific information. Fortunately for windows this is
* super basic stuff */
struct gl_windowinfo {
HWND hwnd;
HDC hdc;
};
/* Like the other subsystems, the GL subsystem has one swap chain created by
* default. */
struct gl_platform {
HGLRC hrc;
struct gl_windowinfo window;
};
/* For now, only support basic 32bit formats for graphics output. */
static inline int get_color_format_bits(enum gs_color_format format)
{
switch ((uint32_t)format) {
case GS_RGBA:
return 32;
default:
return 0;
}
}
static inline int get_depth_format_bits(enum gs_zstencil_format zsformat)
{
switch ((uint32_t)zsformat) {
case GS_Z16:
return 16;
case GS_Z24_S8:
return 24;
default:
return 0;
}
}
static inline int get_stencil_format_bits(enum gs_zstencil_format zsformat)
{
switch ((uint32_t)zsformat) {
case GS_Z24_S8:
return 8;
default:
return 0;
}
}
/* would use designated initializers but microsoft sort of sucks */
static inline void init_dummy_pixel_format(PIXELFORMATDESCRIPTOR *pfd)
{
memset(pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
pfd->nSize = sizeof(pfd);
pfd->nVersion = 1;
pfd->iPixelType = PFD_TYPE_RGBA;
pfd->cColorBits = 32;
pfd->cDepthBits = 24;
pfd->cStencilBits = 8;
pfd->iLayerType = PFD_MAIN_PLANE;
pfd->dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER;
}
static const char *dummy_window_class = "GLDummyWindow";
static bool registered_dummy_window_class = false;
struct dummy_context {
HWND hwnd;
HGLRC hrc;
HDC hdc;
};
/* Need a dummy window for the dummy context */
static bool gl_register_dummy_window_class(void)
{
WNDCLASSA wc;
if (registered_dummy_window_class)
return true;
memset(&wc, 0, sizeof(wc));
wc.style = CS_OWNDC;
wc.hInstance = GetModuleHandle(NULL);
wc.lpfnWndProc = DefWindowProc;
wc.lpszClassName = dummy_window_class;
if (!RegisterClassA(&wc)) {
blog(LOG_ERROR, "Could not create dummy window class");
return false;
}
registered_dummy_window_class = true;
return true;
}
static inline HWND gl_create_dummy_window(void)
{
HWND hwnd = CreateWindowExA(0, dummy_window_class, "Dummy GL Window",
WS_POPUP,
0, 0, 2, 2,
NULL, NULL, GetModuleHandle(NULL), NULL);
if (!hwnd)
blog(LOG_ERROR, "Could not create dummy context window");
return hwnd;
}
static inline bool wgl_make_current(HDC hdc, HGLRC hglrc)
{
bool success = wglMakeCurrent(hdc, hglrc);
if (!success)
blog(LOG_ERROR, "wglMakeCurrent failed, GetLastError "
"returned %lu", GetLastError());
return success;
}
static inline HGLRC gl_init_basic_context(HDC hdc)
{
HGLRC hglrc = wglCreateContext(hdc);
if (!hglrc) {
blog(LOG_ERROR, "wglCreateContext failed, %lu", GetLastError());
return NULL;
}
if (!wgl_make_current(hdc, hglrc)) {
wglDeleteContext(hglrc);
return NULL;
}
return hglrc;
}
static const int attribs[] =
{
#ifdef _DEBUG
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB,
#endif
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0, 0
};
static inline HGLRC gl_init_context(HDC hdc)
{
#ifdef _DEBUG
if (GLAD_WGL_ARB_create_context) {
HGLRC hglrc = wglCreateContextAttribsARB(hdc, 0, attribs);
if (!hglrc) {
blog(LOG_ERROR, "wglCreateContextAttribsARB failed, "
"%lu", GetLastError());
return NULL;
}
if (!wgl_make_current(hdc, hglrc)) {
wglDeleteContext(hglrc);
return NULL;
}
return hglrc;
}
#endif
return gl_init_basic_context(hdc);
}
static bool gl_dummy_context_init(struct dummy_context *dummy)
{
PIXELFORMATDESCRIPTOR pfd;
int format_index;
if (!gl_register_dummy_window_class())
return false;
dummy->hwnd = gl_create_dummy_window();
if (!dummy->hwnd)
return false;
dummy->hdc = GetDC(dummy->hwnd);
init_dummy_pixel_format(&pfd);
format_index = ChoosePixelFormat(dummy->hdc, &pfd);
if (!format_index) {
blog(LOG_ERROR, "Dummy ChoosePixelFormat failed, %lu",
GetLastError());
return false;
}
if (!SetPixelFormat(dummy->hdc, format_index, &pfd)) {
blog(LOG_ERROR, "Dummy SetPixelFormat failed, %lu",
GetLastError());
return false;
}
dummy->hrc = gl_init_basic_context(dummy->hdc);
if (!dummy->hrc) {
blog(LOG_ERROR, "Failed to initialize dummy context");
return false;
}
return true;
}
static inline void gl_dummy_context_free(struct dummy_context *dummy)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(dummy->hrc);
DestroyWindow(dummy->hwnd);
memset(dummy, 0, sizeof(struct dummy_context));
}
static inline void required_extension_error(const char *extension)
{
blog(LOG_ERROR, "OpenGL extension %s is required", extension);
}
static bool gl_init_extensions(HDC hdc)
{
if (!gladLoadWGL(hdc)) {
blog(LOG_ERROR, "Failed to load WGL entry functions.");
return false;
}
if (!GLAD_WGL_ARB_pixel_format) {
required_extension_error("ARB_pixel_format");
return false;
}
if (!GLAD_WGL_ARB_create_context) {
required_extension_error("ARB_create_context");
return false;
}
if (!GLAD_WGL_ARB_create_context_profile) {
required_extension_error("ARB_create_context_profile");
return false;
}
return true;
}
static inline void add_attrib(struct darray *list, int attrib, int val)
{
darray_push_back(sizeof(int), list, &attrib);
darray_push_back(sizeof(int), list, &val);
}
/* Creates the real pixel format for the target window */
static int gl_choose_pixel_format(HDC hdc, const struct gs_init_data *info)
{
struct darray attribs;
int color_bits = get_color_format_bits(info->format);
int depth_bits = get_depth_format_bits(info->zsformat);
int stencil_bits = get_stencil_format_bits(info->zsformat);
UINT num_formats;
BOOL success;
int format;
if (!color_bits) {
blog(LOG_ERROR, "gl_init_pixel_format: color format not "
"supported");
return false;
}
darray_init(&attribs);
add_attrib(&attribs, WGL_DRAW_TO_WINDOW_ARB, GL_TRUE);
add_attrib(&attribs, WGL_SUPPORT_OPENGL_ARB, GL_TRUE);
add_attrib(&attribs, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB);
add_attrib(&attribs, WGL_DOUBLE_BUFFER_ARB, GL_TRUE);
add_attrib(&attribs, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB);
add_attrib(&attribs, WGL_COLOR_BITS_ARB, color_bits);
add_attrib(&attribs, WGL_DEPTH_BITS_ARB, depth_bits);
add_attrib(&attribs, WGL_STENCIL_BITS_ARB, stencil_bits);
add_attrib(&attribs, 0, 0);
success = wglChoosePixelFormatARB(hdc, attribs.array, NULL, 1, &format,
&num_formats);
if (!success || !num_formats) {
blog(LOG_ERROR, "wglChoosePixelFormatARB failed, %lu",
GetLastError());
format = 0;
}
darray_free(&attribs);
return format;
}
static inline bool gl_getpixelformat(HDC hdc, const struct gs_init_data *info,
int *format, PIXELFORMATDESCRIPTOR *pfd)
{
if (!format)
return false;
*format = gl_choose_pixel_format(hdc, info);
if (!DescribePixelFormat(hdc, *format, sizeof(*pfd), pfd)) {
blog(LOG_ERROR, "DescribePixelFormat failed, %lu",
GetLastError());
return false;
}
return true;
}
static inline bool gl_setpixelformat(HDC hdc, int format,
PIXELFORMATDESCRIPTOR *pfd)
{
if (!SetPixelFormat(hdc, format, pfd)) {
blog(LOG_ERROR, "SetPixelFormat failed, %lu", GetLastError());
return false;
}
return true;
}
static struct gl_windowinfo *gl_windowinfo_bare(const struct gs_init_data *info)
{
struct gl_windowinfo *wi = bzalloc(sizeof(struct gl_windowinfo));
wi->hwnd = info->window.hwnd;
wi->hdc = GetDC(wi->hwnd);
if (!wi->hdc) {
blog(LOG_ERROR, "Unable to get device context from window");
bfree(wi);
return NULL;
}
return wi;
}
#define DUMMY_WNDCLASS "Dummy GL Window Class"
static bool register_dummy_class(void)
{
static bool created = false;
WNDCLASSA wc = {0};
wc.style = CS_OWNDC;
wc.hInstance = GetModuleHandleW(NULL);
wc.lpfnWndProc = (WNDPROC)DefWindowProcA;
wc.lpszClassName = DUMMY_WNDCLASS;
if (created)
return true;
if (!RegisterClassA(&wc)) {
blog(LOG_ERROR, "Failed to register dummy GL window class, %lu",
GetLastError());
return false;
}
created = true;
return true;
}
static bool create_dummy_window(struct gl_platform *plat)
{
plat->window.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS,
"OpenGL Dummy Window", WS_POPUP, 0, 0, 1, 1,
NULL, NULL, GetModuleHandleW(NULL), NULL);
if (!plat->window.hwnd) {
blog(LOG_ERROR, "Failed to create dummy GL window, %lu",
GetLastError());
return false;
}
plat->window.hdc = GetDC(plat->window.hwnd);
if (!plat->window.hdc) {
blog(LOG_ERROR, "Failed to get dummy GL window DC (%lu)",
GetLastError());
return false;
}
return true;
}
static bool init_default_swap(struct gl_platform *plat, gs_device_t *device,
int pixel_format, PIXELFORMATDESCRIPTOR *pfd)
{
if (!gl_setpixelformat(plat->window.hdc, pixel_format, pfd))
return false;
return true;
}
void gl_update(gs_device_t *device)
{
/* does nothing on windows */
UNUSED_PARAMETER(device);
}
static void init_dummy_swap_info(struct gs_init_data *info)
{
info->format = GS_RGBA;
info->zsformat = GS_ZS_NONE;
}
struct gl_platform *gl_platform_create(gs_device_t *device, uint32_t adapter)
{
struct gl_platform *plat = bzalloc(sizeof(struct gl_platform));
struct dummy_context dummy;
struct gs_init_data info = {0};
int pixel_format;
PIXELFORMATDESCRIPTOR pfd;
memset(&dummy, 0, sizeof(struct dummy_context));
init_dummy_swap_info(&info);
if (!gl_dummy_context_init(&dummy))
goto fail;
if (!gl_init_extensions(dummy.hdc))
goto fail;
if (!register_dummy_class())
return false;
if (!create_dummy_window(plat))
return false;
/* you have to have a dummy context open before you can actually
* use wglChoosePixelFormatARB */
if (!gl_getpixelformat(dummy.hdc, &info, &pixel_format, &pfd))
goto fail;
gl_dummy_context_free(&dummy);
if (!init_default_swap(plat, device, pixel_format, &pfd))
goto fail;
plat->hrc = gl_init_context(plat->window.hdc);
if (!plat->hrc)
goto fail;
if (!gladLoadGL()) {
blog(LOG_ERROR, "Failed to initialize OpenGL entry functions.");
goto fail;
}
UNUSED_PARAMETER(adapter);
return plat;
fail:
blog(LOG_ERROR, "gl_platform_create failed");
gl_platform_destroy(plat);
gl_dummy_context_free(&dummy);
return NULL;
}
void gl_platform_destroy(struct gl_platform *plat)
{
if (plat) {
if (plat->hrc) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(plat->hrc);
}
if (plat->window.hdc)
ReleaseDC(plat->window.hwnd, plat->window.hdc);
if (plat->window.hwnd)
DestroyWindow(plat->window.hwnd);
bfree(plat);
}
}
bool gl_platform_init_swapchain(struct gs_swap_chain *swap)
{
UNUSED_PARAMETER(swap);
return true;
}
void gl_platform_cleanup_swapchain(struct gs_swap_chain *swap)
{
UNUSED_PARAMETER(swap);
}
struct gl_windowinfo *gl_windowinfo_create(const struct gs_init_data *info)
{
struct gl_windowinfo *wi = gl_windowinfo_bare(info);
PIXELFORMATDESCRIPTOR pfd;
int pixel_format;
if (!wi)
return NULL;
if (!gl_getpixelformat(wi->hdc, info, &pixel_format, &pfd))
goto fail;
if (!gl_setpixelformat(wi->hdc, pixel_format, &pfd))
goto fail;
return wi;
fail:
blog(LOG_ERROR, "gl_windowinfo_create failed");
gl_windowinfo_destroy(wi);
return NULL;
}
void gl_windowinfo_destroy(struct gl_windowinfo *wi)
{
if (wi) {
if (wi->hdc)
ReleaseDC(wi->hwnd, wi->hdc);
bfree(wi);
}
}
void device_enter_context(gs_device_t *device)
{
HDC hdc = device->plat->window.hdc;
if (device->cur_swap)
hdc = device->cur_swap->wi->hdc;
if (!wgl_make_current(hdc, device->plat->hrc))
blog(LOG_ERROR, "device_load_swapchain (GL) failed");
}
void device_leave_context(gs_device_t *device)
{
wglMakeCurrent(NULL, NULL);
UNUSED_PARAMETER(device);
}
void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swap)
{
HDC hdc = device->plat->window.hdc;
if (device->cur_swap == swap)
return;
device->cur_swap = swap;
if (swap)
hdc = swap->wi->hdc;
if (hdc) {
if (!wgl_make_current(hdc, device->plat->hrc))
blog(LOG_ERROR, "device_load_swapchain (GL) failed");
}
}
void device_present(gs_device_t *device)
{
if (!SwapBuffers(device->cur_swap->wi->hdc)) {
blog(LOG_ERROR, "SwapBuffers failed, GetLastError "
"returned %lu", GetLastError());
blog(LOG_ERROR, "device_present (GL) failed");
}
}
extern void gl_getclientsize(const struct gs_swap_chain *swap,
uint32_t *width, uint32_t *height)
{
RECT rc;
if (swap) {
GetClientRect(swap->wi->hwnd, &rc);
*width = rc.right;
*height = rc.bottom;
} else {
*width = 0;
*height = 0;
}
}
EXPORT bool device_gdi_texture_available(void)
{
return false;
}
EXPORT bool device_shared_texture_available(void)
{
return false;
}

600
libobs-opengl/gl-x11.c Normal file
View file

@ -0,0 +1,600 @@
/******************************************************************************
Copyright (C) 2014 by Zachary Lund <admin@computerquip.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
/* Version 2 of the GLX backend...
* Difference from version 1 is that we use XCB to help alleviate
* pains in a threaded environment that is prone to error.
* These errors must be readable and handled for the sake of,
* not only the users' sanity, but my own.
*
* With that said, we have more error checking capabilities...
* and not all of them are used to help simplify current code.
*
* TODO: Implement more complete error checking.
* NOTE: GLX loading functions are placed illogically
* for the sake of convenience.
*/
#include <X11/Xlib.h>
#include <X11/Xlib-xcb.h>
#include <xcb/xcb.h>
#include <stdio.h>
#include "gl-subsystem.h"
#include <glad/glad_glx.h>
static const int ctx_attribs[] = {
#ifdef _DEBUG
GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB,
#endif
GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 2,
None,
};
static int ctx_pbuffer_attribs[] = {
GLX_PBUFFER_WIDTH, 2,
GLX_PBUFFER_HEIGHT, 2,
None
};
static int ctx_visual_attribs[] = {
GLX_STENCIL_SIZE, 0,
GLX_DEPTH_SIZE, 0,
GLX_BUFFER_SIZE, 32,
GLX_DOUBLEBUFFER, true,
GLX_X_RENDERABLE, true,
None
};
struct gl_windowinfo {
/* We store this value since we can fetch a lot
* of information not only concerning the config
* but the visual, and various other settings
* for the context.
*/
GLXFBConfig config;
/* Windows in X11 are defined with integers (XID).
* xcb_window_t is a define for this... they are
* compatible with Xlib as well.
*/
xcb_window_t window;
/* We can't fetch screen without a request so we cache it. */
int screen;
};
struct gl_platform {
Display *display;
GLXContext context;
GLXPbuffer pbuffer;
};
static void print_info_stuff(const struct gs_init_data *info)
{
blog( LOG_INFO,
"X and Y: %i %i\n"
"Backbuffers: %i\n"
"Color Format: %i\n"
"ZStencil Format: %i\n"
"Adapter: %i\n",
info->cx, info->cy,
info->num_backbuffers,
info->format, info->zsformat,
info->adapter
);
}
/* The following utility functions are copied verbatim from WGL code.
* GLX and WGL are more similar than most people realize. */
/* For now, only support basic 32bit formats for graphics output. */
static inline int get_color_format_bits(enum gs_color_format format)
{
switch ((uint32_t)format) {
case GS_RGBA:
return 32;
default:
return 0;
}
}
static inline int get_depth_format_bits(enum gs_zstencil_format zsformat)
{
switch ((uint32_t)zsformat) {
case GS_Z16:
return 16;
case GS_Z24_S8:
return 24;
default:
return 0;
}
}
static inline int get_stencil_format_bits(enum gs_zstencil_format zsformat)
{
switch ((uint32_t)zsformat) {
case GS_Z24_S8:
return 8;
default:
return 0;
}
}
/*
* Since we cannot take advantage of the asynchronous nature of xcb,
* all of the helper functions are synchronous but thread-safe.
*
* They check for errors and will return 0 on problems
* with the exception of when 0 is a valid return value... in which case
* read the specific function comments.
*/
/* Returns -1 on invalid screen. */
static int get_screen_num_from_xcb_screen(xcb_connection_t *xcb_conn,
xcb_screen_t *screen)
{
xcb_screen_iterator_t iter =
xcb_setup_roots_iterator(xcb_get_setup(xcb_conn));
int screen_num = 0;
for (; iter.rem; xcb_screen_next(&iter), ++screen_num)
if (iter.data == screen)
return screen_num;
return -1;
}
static xcb_screen_t *get_screen_from_root(xcb_connection_t *xcb_conn,
xcb_window_t root)
{
xcb_screen_iterator_t iter =
xcb_setup_roots_iterator(xcb_get_setup(xcb_conn));
while (iter.rem) {
if (iter.data->root == root)
return iter.data;
xcb_screen_next(&iter);
}
return 0;
}
static inline int get_screen_num_from_root(xcb_connection_t *xcb_conn,
xcb_window_t root)
{
xcb_screen_t *screen = get_screen_from_root(xcb_conn, root);
if (!screen) return -1;
return get_screen_num_from_xcb_screen(xcb_conn, screen);
}
static xcb_get_geometry_reply_t* get_window_geometry(
xcb_connection_t *xcb_conn, xcb_drawable_t drawable)
{
xcb_get_geometry_cookie_t cookie;
xcb_generic_error_t *error;
xcb_get_geometry_reply_t *reply;
cookie = xcb_get_geometry(xcb_conn, drawable);
reply = xcb_get_geometry_reply(xcb_conn, cookie, &error);
if (error) {
blog(LOG_ERROR, "Failed to fetch parent window geometry!");
free(error);
free(reply);
return 0;
}
free(error);
return reply;
}
static bool gl_context_create(struct gl_platform *plat)
{
Display *display = plat->display;
int frame_buf_config_count = 0;
GLXFBConfig *config = NULL;
GLXContext context;
bool success = false;
if (!GLAD_GLX_ARB_create_context) {
blog(LOG_ERROR, "ARB_GLX_create_context not supported!");
return false;
}
config = glXChooseFBConfig(display, DefaultScreen(display),
ctx_visual_attribs, &frame_buf_config_count);
if (!config) {
blog(LOG_ERROR, "Failed to create OpenGL frame buffer config");
return false;
}
context = glXCreateContextAttribsARB(display, config[0], NULL,
true, ctx_attribs);
if (!context) {
blog(LOG_ERROR, "Failed to create OpenGL context.");
goto error;
}
plat->context = context;
plat->display = display;
plat->pbuffer = glXCreatePbuffer(display, config[0],
ctx_pbuffer_attribs);
if (!plat->pbuffer) {
blog(LOG_ERROR, "Failed to create OpenGL pbuffer");
goto error;
}
success = true;
error:
XFree(config);
XSync(display, false);
return success;
}
static void gl_context_destroy(struct gl_platform *plat)
{
Display *display = plat->display;
glXMakeContextCurrent(display, None, None, NULL);
glXDestroyContext(display, plat->context);
bfree(plat);
}
extern struct gl_windowinfo *gl_windowinfo_create(const struct gs_init_data *info)
{
UNUSED_PARAMETER(info);
return bmalloc(sizeof(struct gl_windowinfo));
}
extern void gl_windowinfo_destroy(struct gl_windowinfo *info)
{
UNUSED_PARAMETER(info);
bfree(info);
}
static Display *open_windowless_display(void)
{
Display *display = XOpenDisplay(NULL);
xcb_connection_t *xcb_conn;
xcb_screen_iterator_t screen_iterator;
xcb_screen_t *screen;
int screen_num;
if (!display) {
blog(LOG_ERROR, "Unable to open new X connection!");
return NULL;
}
xcb_conn = XGetXCBConnection(display);
if (!xcb_conn) {
blog(LOG_ERROR, "Unable to get XCB connection to main display");
goto error;
}
screen_iterator = xcb_setup_roots_iterator(xcb_get_setup(xcb_conn));
screen = screen_iterator.data;
if (!screen) {
blog(LOG_ERROR, "Unable to get screen root");
goto error;
}
screen_num = get_screen_num_from_root(xcb_conn, screen->root);
if (screen_num == -1) {
blog(LOG_ERROR, "Unable to get screen number from root");
goto error;
}
if (!gladLoadGLX(display, screen_num)) {
blog(LOG_ERROR, "Unable to load GLX entry functions.");
goto error;
}
return display;
error:
if (display)
XCloseDisplay(display);
return NULL;
}
static int x_error_handler(Display *display, XErrorEvent *error)
{
char str[512];
XGetErrorText(display, error->error_code, str, sizeof(str));
blog(LOG_ERROR, "X Error: %s", str);
return 0;
}
extern struct gl_platform *gl_platform_create(gs_device_t *device,
uint32_t adapter)
{
/* There's some trickery here... we're mixing libX11, xcb, and GLX
For an explanation see here: http://xcb.freedesktop.org/MixingCalls/
Essentially, GLX requires Xlib. Everything else we use xcb. */
struct gl_platform * plat = bmalloc(sizeof(struct gl_platform));
Display * display = open_windowless_display();
if (!display) {
goto fail_display_open;
}
XSetEventQueueOwner(display, XCBOwnsEventQueue);
XSetErrorHandler(x_error_handler);
/* We assume later that cur_swap is already set. */
device->plat = plat;
plat->display = display;
if (!gl_context_create(plat)) {
blog(LOG_ERROR, "Failed to create context!");
goto fail_context_create;
}
if (!glXMakeContextCurrent(plat->display, plat->pbuffer, plat->pbuffer,
plat->context)) {
blog(LOG_ERROR, "Failed to make context current.");
goto fail_make_current;
}
if (!gladLoadGL()) {
blog(LOG_ERROR, "Failed to load OpenGL entry functions.");
goto fail_load_gl;
}
blog(LOG_INFO, "OpenGL version: %s\n", glGetString(GL_VERSION));
goto success;
fail_make_current:
gl_context_destroy(plat);
fail_context_create:
fail_load_gl:
XCloseDisplay(display);
fail_display_open:
bfree(plat);
plat = NULL;
success:
UNUSED_PARAMETER(adapter);
return plat;
}
extern void gl_platform_destroy(struct gl_platform *plat)
{
if (!plat) /* In what case would platform be invalid here? */
return;
gl_context_destroy(plat);
}
extern bool gl_platform_init_swapchain(struct gs_swap_chain *swap)
{
Display *display = swap->device->plat->display;
xcb_connection_t *xcb_conn = XGetXCBConnection(display);
xcb_window_t wid = xcb_generate_id(xcb_conn);
xcb_window_t parent = swap->info.window.id;
xcb_get_geometry_reply_t *geometry =
get_window_geometry(xcb_conn, parent);
bool status = false;
int screen_num;
int visual;
GLXFBConfig *fb_config;
if (!geometry) goto fail_geometry_request;
screen_num = get_screen_num_from_root(xcb_conn, geometry->root);
if (screen_num == -1) {
goto fail_screen;
}
/* ...fetch the best match... */
{
int num_configs;
fb_config = glXChooseFBConfig(display, screen_num,
ctx_visual_attribs, &num_configs);
if (!fb_config || !num_configs) {
blog(LOG_ERROR, "Failed to find FBConfig!");
goto fail_fb_config;
}
}
/* ...then fetch matching visual info for xcb. */
{
int error = glXGetFBConfigAttrib(display, fb_config[0], GLX_VISUAL_ID, &visual);
if (error) {
blog(LOG_ERROR, "Bad call to GetFBConfigAttrib!");
goto fail_visual_id;
}
}
xcb_colormap_t colormap = xcb_generate_id(xcb_conn);
uint32_t mask = XCB_CW_BORDER_PIXEL | XCB_CW_COLORMAP;
uint32_t mask_values[] = { 0, colormap, 0 };
xcb_create_colormap(xcb_conn,
XCB_COLORMAP_ALLOC_NONE,
colormap,
parent,
visual
);
xcb_create_window(
xcb_conn, 24 /* Hardcoded? */,
wid, parent,
0, 0,
geometry->width,
geometry->height,
0, 0,
visual, mask, mask_values
);
swap->wi->config = fb_config[0];
swap->wi->window = wid;
xcb_map_window(xcb_conn, wid);
XFree(fb_config);
status = true;
goto success;
fail_visual_id:
XFree(fb_config);
fail_fb_config:
fail_screen:
fail_geometry_request:
success:
free(geometry);
return status;
}
extern void gl_platform_cleanup_swapchain(struct gs_swap_chain *swap)
{
UNUSED_PARAMETER(swap);
/* Really nothing to clean up? */
}
extern void device_enter_context(gs_device_t *device)
{
GLXContext context = device->plat->context;
Display *display = device->plat->display;
if (device->cur_swap) {
XID window = device->cur_swap->wi->window;
if (!glXMakeContextCurrent(display, window, window, context)) {
blog(LOG_ERROR, "Failed to make context current.");
}
} else {
GLXPbuffer pbuf = device->plat->pbuffer;
if (!glXMakeContextCurrent(display, pbuf, pbuf, context)) {
blog(LOG_ERROR, "Failed to make context current.");
}
}
}
extern void device_leave_context(gs_device_t *device)
{
Display *display = device->plat->display;
if (!glXMakeContextCurrent(display, None, None, NULL)) {
blog(LOG_ERROR, "Failed to reset current context.");
}
}
extern void gl_getclientsize(const struct gs_swap_chain *swap,
uint32_t *width, uint32_t *height)
{
xcb_connection_t *xcb_conn = XGetXCBConnection(swap->device->plat->display);
xcb_window_t window = swap->wi->window;
xcb_get_geometry_reply_t *geometry = get_window_geometry(xcb_conn, window);
*width = geometry->width;
*height = geometry->height;
free(geometry);
}
extern void gl_update(gs_device_t *device)
{
Display *display = device->plat->display;
xcb_window_t window = device->cur_swap->wi->window;
uint32_t values[] = {
device->cur_swap->info.cx,
device->cur_swap->info.cy
};
xcb_configure_window(
XGetXCBConnection(display), window,
XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT,
values
);
}
extern void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swap)
{
if (device->cur_swap == swap)
return;
Display *dpy = device->plat->display;
GLXContext ctx = device->plat->context;
device->cur_swap = swap;
if (swap) {
XID window = swap->wi->window;
if (!glXMakeContextCurrent(dpy, window, window, ctx)) {
blog(LOG_ERROR, "Failed to make context current.");
}
} else {
GLXPbuffer pbuf = device->plat->pbuffer;
if (!glXMakeContextCurrent(dpy, pbuf, pbuf, ctx)) {
blog(LOG_ERROR, "Failed to make context current.");
}
}
}
enum swap_type {
SWAP_TYPE_NORMAL,
SWAP_TYPE_EXT,
SWAP_TYPE_MESA,
SWAP_TYPE_SGI,
};
extern void device_present(gs_device_t *device)
{
static bool initialized = false;
static enum swap_type swap_type = SWAP_TYPE_NORMAL;
Display *display = device->plat->display;
XID window = device->cur_swap->wi->window;
if (!initialized) {
if (GLAD_GLX_EXT_swap_control)
swap_type = SWAP_TYPE_EXT;
else if (GLAD_GLX_MESA_swap_control)
swap_type = SWAP_TYPE_MESA;
else if (GLAD_GLX_SGI_swap_control)
swap_type = SWAP_TYPE_SGI;
initialized = true;
}
/* TODO: Handle XCB events. */
switch (swap_type) {
case SWAP_TYPE_EXT: glXSwapIntervalEXT(display, window, 0); break;
case SWAP_TYPE_MESA: glXSwapIntervalMESA(0); break;
case SWAP_TYPE_SGI: glXSwapIntervalSGI(0); break;
case SWAP_TYPE_NORMAL:;
}
glXSwapBuffers(display, window);
}

View file

@ -0,0 +1,80 @@
/******************************************************************************
Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "gl-subsystem.h"
static bool gl_init_zsbuffer(struct gs_zstencil_buffer *zs, uint32_t width,
uint32_t height)
{
glGenRenderbuffers(1, &zs->buffer);
if (!gl_success("glGenRenderbuffers"))
return false;
if (!gl_bind_renderbuffer(GL_RENDERBUFFER, zs->buffer))
return false;
glRenderbufferStorage(GL_RENDERBUFFER, zs->format, width, height);
if (!gl_success("glRenderbufferStorage"))
return false;
gl_bind_renderbuffer(GL_RENDERBUFFER, 0);
return true;
}
static inline GLenum get_attachment(enum gs_zstencil_format format)
{
switch (format) {
case GS_Z16: return GL_DEPTH_ATTACHMENT;
case GS_Z24_S8: return GL_DEPTH_STENCIL_ATTACHMENT;
case GS_Z32F: return GL_DEPTH_ATTACHMENT;
case GS_Z32F_S8X24: return GL_DEPTH_STENCIL_ATTACHMENT;
case GS_ZS_NONE: return 0;
}
return 0;
}
gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width,
uint32_t height, enum gs_zstencil_format format)
{
struct gs_zstencil_buffer *zs;
zs = bzalloc(sizeof(struct gs_zstencil_buffer));
zs->format = convert_zstencil_format(format);
zs->attachment = get_attachment(format);
zs->device = device;
if (!gl_init_zsbuffer(zs, width, height)) {
blog(LOG_ERROR, "device_zstencil_create (GL) failed");
gs_zstencil_destroy(zs);
return NULL;
}
return zs;
}
void gs_zstencil_destroy(gs_zstencil_t *zs)
{
if (zs) {
if (zs->buffer) {
glDeleteRenderbuffers(1, &zs->buffer);
gl_success("glDeleteRenderbuffers");
}
bfree(zs);
}
}