source: trunk/src/shader.cpp @ 668

Last change on this file since 668 was 668, checked in by sam, 10 years ago

Protect the Shader constructor and provide a static creation method that
will let us cache shaders.

File size: 2.4 KB
Line 
1//
2// Lol Engine
3//
4// Copyright: (c) 2010-2011 Sam Hocevar <sam@hocevar.net>
5//   This program is free software; you can redistribute it and/or
6//   modify it under the terms of the Do What The Fuck You Want To
7//   Public License, Version 2, as published by Sam Hocevar. See
8//   http://sam.zoy.org/projects/COPYING.WTFPL for more details.
9//
10
11#if defined HAVE_CONFIG_H
12#   include "config.h"
13#endif
14
15#include <cmath>
16#include <cstdio>
17
18#ifdef WIN32
19#   define WIN32_LEAN_AND_MEAN
20#   include <windows.h>
21#endif
22#if defined __APPLE__ && defined __MACH__
23#   include <OpenGL/gl.h>
24#else
25#   define GL_GLEXT_PROTOTYPES
26#   include <GL/gl.h>
27#endif
28
29#include "core.h"
30
31/*
32 * Shader implementation class
33 */
34
35class ShaderData
36{
37    friend class Shader;
38
39private:
40    GLuint prog_id, vert_id, frag_id;
41};
42
43/*
44 * Public Shader class
45 */
46
47Shader *Shader::Create(char const *vert, char const *frag)
48{
49    return new Shader(vert, frag);
50}
51
52void Shader::Destroy(Shader *shader)
53{
54    delete shader;
55}
56
57Shader::Shader(char const *vert, char const *frag)
58  : data(new ShaderData())
59{
60    char buf[4096];
61    GLsizei len;
62
63    data->vert_id = glCreateShader(GL_VERTEX_SHADER);
64    glShaderSource(data->vert_id, 1, &vert, NULL);
65    glCompileShader(data->vert_id);
66
67    glGetShaderInfoLog(data->vert_id, sizeof(buf), &len, buf);
68    if (len > 0)
69        fprintf(stderr, "ERROR: failed to compile vertex shader: %s", buf);
70
71    data->frag_id = glCreateShader(GL_FRAGMENT_SHADER);
72    glShaderSource(data->frag_id, 1, &frag, NULL);
73    glCompileShader(data->frag_id);
74
75    glGetShaderInfoLog(data->frag_id, sizeof(buf), &len, buf);
76    if (len > 0)
77        fprintf(stderr, "ERROR: failed to compile fragment shader: %s", buf);
78
79    data->prog_id = glCreateProgram();
80    glAttachShader(data->prog_id, data->vert_id);
81    glAttachShader(data->prog_id, data->frag_id);
82
83    glLinkProgram(data->prog_id);
84    glValidateProgram(data->prog_id);
85}
86
87int Shader::GetAttribLocation(char const *attr) const
88{
89    return glGetAttribLocation(data->prog_id, attr);
90}
91
92int Shader::GetUniformLocation(char const *uni) const
93{
94    return glGetUniformLocation(data->prog_id, uni);
95}
96
97void Shader::Bind() const
98{
99    glUseProgram(data->prog_id);
100}
101
102Shader::~Shader()
103{
104    glDetachShader(data->prog_id, data->vert_id);
105    glDetachShader(data->prog_id, data->frag_id);
106    glDeleteShader(data->vert_id);
107    glDeleteShader(data->frag_id);
108    glDeleteProgram(data->prog_id);
109    delete data;
110}
111
Note: See TracBrowser for help on using the repository browser.