invisible
view src/sdr.cc @ 21:53fe01a4e2f3
foo - backup
author | Eleni Maria Stea <eleni@mutantstargoat.com> |
---|---|
date | Sun, 10 Nov 2013 14:18:41 +0200 |
parents | f756fc9fdd3e |
children | b50ad2711f5f |
line source
1 #include <GL/glew.h>
2 #include <GL/gl.h>
4 #include <errno.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
9 #include "sdr.h"
11 char* sdr_load(const char* fname)
12 {
13 if(!fname) {
14 return 0;
15 }
17 FILE *fp;
18 int ctr = 0;
20 if(!(fp = fopen(fname, "rb"))) {
21 fprintf(stderr, "Failed to open file %s: %s\n", fname, strerror(errno));
22 return 0;
23 }
24 fseek(fp, 0, SEEK_END);
25 ctr = ftell(fp);
26 rewind(fp);
28 char *glsl = NULL;
29 if(!(glsl = (char*) malloc(ctr + 1))) {
30 perror("Failed to allocate memory");
31 return 0;
32 }
33 ctr = fread(glsl, 1, ctr, fp);
34 fclose(fp);
36 return glsl;
37 }
39 bool sdr_compile(unsigned int sdr)
40 {
41 int status, loglen;
42 char infolog[512];
44 glCompileShader(sdr);
45 glGetShaderiv(sdr, GL_COMPILE_STATUS, &status);
46 glGetShaderInfoLog(sdr, sizeof infolog, &loglen, infolog);
47 if(status == GL_FALSE) {
48 fprintf(stderr, "Failed to compile shader: %s\n", infolog);
49 return false;
50 } else if(loglen) {
51 fprintf(stderr, "%s\n", infolog);
52 }
53 return true;
54 }
56 unsigned int sdr_getprog(const char* vfname, const char* ffname)
57 {
58 char *vsdr_glsl = NULL;
59 char *fsdr_glsl = NULL;
61 GLuint vsdr; GLuint fsdr;
62 vsdr = glCreateShader(GL_VERTEX_SHADER);
63 fsdr = glCreateShader(GL_FRAGMENT_SHADER);
65 if(!(vsdr_glsl = sdr_load(vfname)))
66 return 0;
67 if(!(fsdr_glsl = sdr_load(ffname)))
68 return 0;
70 glShaderSource(vsdr, 1, (const GLchar**)&vsdr_glsl, NULL);
71 glShaderSource(fsdr, 1, (const GLchar**)&fsdr_glsl, NULL);
73 free(vsdr_glsl);
74 free(fsdr_glsl);
76 if(!sdr_compile(vsdr)) {
77 fprintf(stderr, "Shader %s failed to compile.\n", vfname);
78 return 0;
79 }
80 if(!sdr_compile(fsdr)) {
81 fprintf(stderr, "Shader %s failed to compile.\n", ffname);
82 return 0;
83 }
85 unsigned int sprog;
86 int status, loglen;
87 char infolog[512];
89 sprog = glCreateProgram();
90 glAttachShader(sprog, vsdr);
91 glAttachShader(sprog, fsdr);
92 glLinkProgram(sprog);
93 glGetProgramiv(sprog, GL_LINK_STATUS, &status);
94 glGetProgramInfoLog(sprog, sizeof infolog, &loglen, infolog);
95 if(status == GL_FALSE) {
96 fprintf(stderr, "Error while linking shader program:\n%s\n", infolog);
97 return 0;
98 } else if(loglen) {
99 fprintf(stderr, "%s\n", infolog);
100 }
101 return sprog;
102 }