]> git.tdb.fi Git - libs/gl.git/blob - source/program.cpp
Tangent and binormal vectors should use custom transform as well
[libs/gl.git] / source / program.cpp
1 #include <algorithm>
2 #include "arb_shader_objects.h"
3 #include "arb_vertex_shader.h"
4 #include "error.h"
5 #include "extension.h"
6 #include "program.h"
7 #include "shader.h"
8
9 using namespace std;
10
11 namespace {
12
13 const char *standard_vertex_src[] =
14 {
15         "n",   "attribute vec3 tangent;\n",
16         "n",   "attribute vec3 binormal;\n",
17         "t|n", "varying vec2 v_texcoord;\n",
18         "s",   "varying vec3 v_shadowcoord;\n",
19         "!lm", "varying vec4 v_color;\n",
20         "l!n", "varying vec3 v_normal;\n",
21         "l",   "varying vec3 v_light_dir;\n",
22         "p|e", "varying vec3 v_eye_dir;\n",
23         "r",   "vec4 transform_vertex(vec4);\n",
24         "lr",  "vec3 transform_normal(vec3);\n",
25          0,    "void main()\n",
26          0,    "{\n",
27         "r",   "\tvec4 eye_pos = transform_vertex(gl_Vertex);\n",
28         "!r",  "\tvec4 eye_pos = gl_ModelViewMatrix*gl_Vertex;\n",
29          0,    "\tgl_Position = gl_ProjectionMatrix*eye_pos;\n",
30         "lr",  "\tvec3 eye_normal = transform_normal(gl_Normal);\n",
31         "l!r", "\tvec3 eye_normal = gl_NormalMatrix*gl_Normal;\n",
32         "l!n", "\tv_normal = eye_normal;\n",
33         "nr",  "\tvec3 eye_tangent = transform_normal(tangent);\n",
34         "n!r", "\tvec3 eye_tangent = gl_NormalMatrix*tangent;\n",
35         "nr",  "\tvec3 eye_binormal = transform_normal(binormal);\n",
36         "n!r", "\tvec3 eye_binormal = gl_NormalMatrix*binormal;\n",
37         "l",   "\tvec3 eye_light_dir = normalize(gl_LightSource[0].position.xyz-eye_pos.xyz*gl_LightSource[0].position.w);\n",
38         "n",   "\tv_light_dir = vec3(dot(eye_tangent, eye_light_dir), dot(eye_binormal, eye_light_dir), dot(eye_normal, eye_light_dir));\n",
39         "l!n", "\tv_light_dir = eye_light_dir;\n",
40         "p|e", "\tvec3 eye_dir = -normalize(eye_pos.xyz);\n",
41         "p|en",  "\tv_eye_dir = vec3(dot(eye_tangent, eye_dir), dot(eye_binormal, eye_dir), dot(eye_normal, eye_dir));\n",
42         "p|e!n", "\tv_eye_dir = eye_dir;\n",
43         "t|n", "\tv_texcoord = gl_MultiTexCoord0.xy;\n",
44         "s",   "\tv_shadowcoord = vec3(dot(gl_EyePlaneS[3], eye_pos), dot(gl_EyePlaneT[3], eye_pos), dot(gl_EyePlaneR[3], eye_pos));\n",
45         "!lm", "\tv_color = gl_Color;\n",
46          0,    "}",
47         0, 0
48 };
49
50 const char *standard_fragment_src[] =
51 {
52         "t",   "uniform sampler2D texture;\n",
53         "n",   "uniform sampler2D normalmap;\n",
54         "s",   "uniform sampler2DShadow shadow;\n",
55         "e",   "uniform samplerCube environment;\n",
56         "e",   "uniform float reflectivity;\n",
57         "t|n", "varying vec2 v_texcoord;\n",
58         "s",   "varying vec3 v_shadowcoord;\n",
59         "!lm", "varying vec4 v_color;\n",
60         "l!n", "varying vec3 v_normal;\n",
61         "l",   "varying vec3 v_light_dir;\n",
62         "p|e", "varying vec3 v_eye_dir;\n",
63          0,    "void main()\n",
64          0,    "{\n",
65         "n",   "\tvec3 n_normal = texture2D(normalmap, v_texcoord).xyz*2.0-1.0;\n",
66         "l!n", "\tvec3 n_normal = normalize(v_normal);\n",
67         "l",   "\tfloat l_diffuse = max(dot(n_normal, normalize(v_light_dir)), 0.0);\n",
68         "p",   "\tvec3 half_dir = normalize(v_eye_dir+v_light_dir);\n",
69         "p",   "\tfloat l_specular = pow(max(dot(half_dir, n_normal), 0.0), gl_FrontMaterial.shininess);\n",
70         "s",   "\tfloat l_shadow = shadow2D(shadow, v_shadowcoord).r;\n",
71         /* XXX This is incorrect with normal mapping, since the vectors are in TBN
72         space but environment map is expected to be in eye space */
73         "e",   "\tvec4 reflection = textureCube(environment, n_normal*(dot(n_normal, v_eye_dir)*2.0)-v_eye_dir);\n",
74          0,    "\tgl_FragColor = ",
75         "!t!l!m", "vec4(1.0, 1.0, 1.0, 1.0)",
76         "t",     "texture2D(texture, v_texcoord)",
77         "l|mt",  "*",
78         "!lm",   "v_color",
79         "l",     "((l_diffuse",
80         "lm",    "*gl_FrontLightProduct[0].diffuse",
81         "p",     "+l_specular",
82         "pm",    "*gl_FrontLightProduct[0].specular",
83         "l",     ")",
84         "s",     "*l_shadow",
85         "lm",    "+gl_FrontLightModelProduct.sceneColor",
86         "l",     ")",
87         "e",     "+reflection*reflectivity",
88          0,      ";\n",
89          0,    "}\n",
90         0, 0
91 };
92
93 }
94
95 namespace Msp {
96 namespace GL {
97
98 Program::Program()
99 {
100         init();
101 }
102
103 Program::Program(const StandardFeatures &features)
104 {
105         init();
106
107         add_standard_shaders(features);
108         if(!features.transform)
109                 link();
110 }
111
112 Program::Program(const string &vert, const string &frag)
113 {
114         init();
115
116         attach_shader_owned(new Shader(VERTEX_SHADER, vert));
117         attach_shader_owned(new Shader(FRAGMENT_SHADER, frag));
118         link();
119 }
120
121 void Program::init()
122 {
123         static RequireExtension _ext("GL_ARB_shader_objects");
124
125         linked = false;
126         id = glCreateProgramObjectARB();
127 }
128
129 Program::~Program()
130 {
131         for(list<Shader *>::iterator i=owned_data.begin(); i!=owned_data.end(); ++i)
132                 delete *i;
133         glDeleteObjectARB(id);
134 }
135
136 void Program::attach_shader(Shader &shader)
137 {
138         if(find(shaders.begin(), shaders.end(), &shader)==shaders.end())
139         {
140                 glAttachObjectARB(id, shader.get_id());
141                 shaders.push_back(&shader);
142         }
143 }
144
145 void Program::attach_shader_owned(Shader *shader)
146 {
147         attach_shader(*shader);
148         if(find(owned_data.begin(), owned_data.end(), shader)==owned_data.end())
149                 owned_data.push_back(shader);
150 }
151
152 void Program::detach_shader(Shader &shader)
153 {
154         list<Shader *>::iterator i = remove(shaders.begin(), shaders.end(), &shader);
155         if(i!=shaders.end())
156         {
157                 shaders.erase(i, shaders.end());
158                 glDetachObjectARB(id, shader.get_id());
159         }
160 }
161
162 void Program::add_standard_shaders(const StandardFeatures &features)
163 {
164         string flags = features.create_flags();
165         string vertex_src = process_standard_source(standard_vertex_src, flags);
166         string fragment_src = process_standard_source(standard_fragment_src, flags);
167         attach_shader_owned(new Shader(VERTEX_SHADER, vertex_src));
168         attach_shader_owned(new Shader(FRAGMENT_SHADER, fragment_src));
169 }
170
171 string Program::process_standard_source(const char **source, const string &flags)
172 {
173         string result;
174
175         for(unsigned i=0; source[i+1]; i+=2)
176         {
177                 if(source[i])
178                 {
179                         bool cond = true;
180                         char oper = '&';
181                         for(const char *c=source[i]; *c; ++c)
182                         {
183                                 if(*c>='a' && *c<='z')
184                                 {
185                                         bool found = (flags.find(*c)!=string::npos);
186                                         if(oper=='|')
187                                                 cond = (cond || found);
188                                         else if(oper=='!')
189                                                 cond = (cond && !found);
190                                         else if(oper=='&')
191                                                 cond = (cond && found);
192                                         oper = '&';
193                                 }
194                                 else
195                                         oper = *c;
196                         }
197
198                         if(!cond)
199                                 continue;
200                 }
201
202                 result += source[i+1];
203         }
204
205         return result;
206 }
207
208 void Program::bind_attribute(unsigned index, const string &name)
209 {
210         static RequireExtension _ext("GL_ARB_vertex_shader");
211         glBindAttribLocationARB(id, index, name.c_str());
212 }
213
214 void Program::link()
215 {
216         for(list<Shader *>::iterator i=shaders.begin(); i!=shaders.end(); ++i)
217                 if(!(*i)->is_compiled())
218                         (*i)->compile();
219
220         uniforms.clear();
221
222         glLinkProgramARB(id);
223         int value;
224         glGetObjectParameterivARB(id, GL_OBJECT_LINK_STATUS_ARB, &value);
225         if(!(linked = value))
226                 throw compile_error(get_info_log());
227
228         glGetObjectParameterivARB(id, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &value);
229         for(int i=0; i<value; ++i)
230         {
231                 UniformInfo info;
232                 char name[128];
233                 int len = 0;
234                 glGetActiveUniformARB(id, i, 128, &len, &info.size, &info.type, name);
235                 if(len)
236                 {
237                         info.name = name;
238                         info.location = glGetUniformLocationARB(id, name);
239                         uniforms[name] = info;
240                 }
241         }
242 }
243
244 string Program::get_info_log() const
245 {
246         GLsizei len = 0;
247         glGetObjectParameterivARB(id, GL_OBJECT_INFO_LOG_LENGTH_ARB, &len);
248         char *buf = new char[len+1];
249         glGetInfoLogARB(id, len+1, &len, buf);
250         string log(buf, len);
251         delete[] buf;
252         return log;
253 }
254
255 void Program::bind() const
256 {
257         if(!linked)
258                 throw invalid_operation("Program::bind");
259
260         if(!set_current(this))
261                 return;
262
263         glUseProgramObjectARB(id);
264 }
265
266 int Program::get_uniform_location(const string &n) const
267 {
268         map<string, UniformInfo>::const_iterator i = uniforms.find(n);
269         if(i==uniforms.end())
270         {
271                 if(n[n.size()-1]==']')
272                 {
273                         string::size_type open_bracket = n.rfind('[');
274                         if(open_bracket!=string::npos)
275                         {
276                                 /* The requested name looks like an array.  glGetActiveUniform only
277                                 gives us the first element of the array, so try to look that up and
278                                 add an offset. */
279                                 int offset = lexical_cast<unsigned>(n.substr(open_bracket+1, n.size()-2-open_bracket));
280                                 i = uniforms.find(n.substr(0, open_bracket)+"[0]");
281                                 if(i!=uniforms.end() && offset<i->second.size)
282                                         return i->second.location+offset;
283                         }
284                 }
285                 return -1;
286         }
287
288         return i->second.location;
289 }
290
291 void Program::unbind()
292 {
293         if(!set_current(0))
294                 return;
295
296         glUseProgramObjectARB(0);
297 }
298
299
300 Program::StandardFeatures::StandardFeatures():
301         texture(false),
302         material(false),
303         lighting(false),
304         specular(false),
305         normalmap(false),
306         shadow(false),
307         reflection(false),
308         transform(false)
309 { }
310
311 string Program::StandardFeatures::create_flags() const
312 {
313         string flags;
314         if(texture)
315                 flags += 't';
316         if(material)
317                 flags += 'm';
318         if(lighting)
319         {
320                 flags += 'l';
321                 if(specular)
322                         flags += 'p';
323                 if(normalmap)
324                         flags += 'n';
325         }
326         if(shadow)
327                 flags += 's';
328         if(reflection)
329                 flags += 'e';
330         if(transform)
331                 flags += 'r';
332
333         return flags;
334 }
335
336
337 Program::Loader::Loader(Program &p):
338         DataFile::ObjectLoader<Program>(p)
339 {
340         add("attribute",       &Loader::attribute);
341         add("fragment_shader", &Loader::fragment_shader);
342         add("standard",        &Loader::standard);
343         add("vertex_shader",   &Loader::vertex_shader);
344 }
345
346 void Program::Loader::finish()
347 {
348         obj.link();
349 }
350
351 void Program::Loader::attribute(unsigned i, const string &n)
352 {
353         obj.bind_attribute(i, n);
354 }
355
356 void Program::Loader::fragment_shader(const string &src)
357 {
358         obj.attach_shader_owned(new Shader(FRAGMENT_SHADER, src));
359 }
360
361 void Program::Loader::standard()
362 {
363         StandardFeatures feat;
364         load_sub(feat);
365         obj.add_standard_shaders(feat);
366 }
367
368 void Program::Loader::vertex_shader(const string &src)
369 {
370         obj.attach_shader_owned(new Shader(VERTEX_SHADER, src));
371 }
372
373
374 Program::StandardFeatures::Loader::Loader(StandardFeatures &f):
375         DataFile::ObjectLoader<StandardFeatures>(f)
376 {
377         add("lighting",  &StandardFeatures::lighting);
378         add("material",  &StandardFeatures::material);
379         add("normalmap", &StandardFeatures::normalmap);
380         add("shadow",    &StandardFeatures::shadow);
381         add("specular",  &StandardFeatures::specular);
382         add("texture",   &StandardFeatures::texture);
383         add("transform", &StandardFeatures::transform);
384 }
385
386 } // namespace GL
387 } // namespace Msp