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