program.cc (2520B)
1 /* Copyright 2013 Brian Swetland <swetland@frotz.net> 2 * 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include <stdio.h> 17 #include <stdlib.h> 18 #include <string.h> 19 20 #include "app.h" 21 #include "util.h" 22 #include "program.h" 23 24 static int check_compile_error(GLuint obj, const char *fn) { 25 GLint r, len; 26 char *buf; 27 28 if (fn) glGetShaderiv(obj, GL_COMPILE_STATUS, &r); 29 else glGetProgramiv(obj, GL_LINK_STATUS, &r); 30 31 if (r) return 0; 32 33 if (fn) glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &len); 34 else glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &len); 35 36 buf = (char*) malloc(len + 1); 37 memset(buf, 0, len); 38 if (buf != 0) { 39 if (fn) glGetShaderInfoLog(obj, len, &len, buf); 40 else glGetProgramInfoLog(obj, len, &len, buf); 41 buf[len] = 0; 42 } 43 fprintf(stderr,"Shader %s Error:\n%s\n", 44 fn ? "Compile" : "Link", buf ? buf : "???"); 45 46 free(buf); 47 return -1; 48 } 49 50 static int shader_compile(const char *vshader, const char *fshader, 51 GLuint *_pgm, GLuint *_vshd, GLuint *_fshd) { 52 GLuint pgm, vshd, fshd; 53 54 pgm = glCreateProgram(); 55 vshd = glCreateShader(GL_VERTEX_SHADER); 56 fshd = glCreateShader(GL_FRAGMENT_SHADER); 57 glShaderSource(vshd, 1, &vshader, NULL); 58 glShaderSource(fshd, 1, &fshader, NULL); 59 glCompileShader(vshd); 60 check_compile_error(vshd, vshader); 61 62 glCompileShader(fshd); 63 check_compile_error(fshd, fshader); 64 65 glAttachShader(pgm, vshd); 66 glAttachShader(pgm, fshd); 67 glLinkProgram(pgm); 68 if (check_compile_error(pgm, 0)) 69 return -1; 70 71 *_pgm = pgm; 72 *_vshd = vshd; 73 *_fshd = fshd; 74 return 0; 75 } 76 77 Program::Program() : vsrc(NULL), fsrc(NULL), status(-1) { 78 } 79 80 int Program::compile(const char *vfn, const char *ffn) { 81 if (!(vsrc = (const char*) load_file(vfn, 0))) 82 return -1; 83 if (!(fsrc = (const char*) load_file(ffn, 0))) 84 return -1; 85 if (shader_compile(vsrc, fsrc, &pobj, &vobj, &fobj)) 86 return -1; 87 status = 0; 88 return 0; 89 } 90 91 int Program::compileStr(const char *vsc, const char *fsc) { 92 vsrc = vsc; 93 fsrc = fsc; 94 if (shader_compile(vsrc, fsrc, &pobj, &vobj, &fobj)) 95 return -1; 96 status = 0; 97 return 0; 98 } 99 100