-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cpp
More file actions
543 lines (495 loc) · 20 KB
/
Program.cpp
File metadata and controls
543 lines (495 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/*
Hale: support for minimalist scientific visualization
Copyright (C) 2014, 2015 University of Chicago
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software. Permission is granted to anyone to
use this software for any purpose, including commercial applications, and
to alter it and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "Hale.h"
#include "privateHale.h"
namespace Hale {
/* gadgets to map uniform names to variables */
std::map<std::string, float> stickyUniformFloat;
std::map<std::string, glm::vec3> stickyUniformVec3;
std::map<std::string, glm::vec4> stickyUniformVec4;
std::map<std::string, glm::mat3> stickyUniformMat3;
std::map<std::string, glm::mat4> stickyUniformMat4;
// #define VERSION "#version 150 core\n "
#define VERSION "#version 410\n "
static const char *AmbDiff_vert
= (VERSION "uniform mat4 projectMat;\n "
"uniform mat4 viewMat;\n "
"uniform mat4 modelMat;\n "
"in vec4 positionVA;\n "
"in vec3 normalVA;\n "
"in vec4 colorVA;\n "
"layout(location = 0) out vec3 norm_frag;\n "
"layout(location = 1) out vec4 color_frag;\n "
// HEY this needs fixing, like the one below
"mat4 modIT = transpose(inverse(modelMat));\n "
"void main(void) {\n "
" gl_Position = projectMat * viewMat * modelMat * positionVA;\n "
" norm_frag = mat3(modIT) * normalVA;\n "
" color_frag = colorVA;\n "
"}\n ");
static const char *AmbDiffSolid_vert
= (VERSION "uniform mat4 projectMat;\n "
"uniform mat4 viewMat;\n "
"uniform mat4 modelMat;\n "
"uniform mat3 model3IT;\n "
"uniform vec4 colorSolid;\n "
"in vec4 positionVA;\n "
"in vec3 normalVA;\n "
"layout(location = 0) out vec3 norm_frag;\n "
"layout(location = 1) out vec4 color_frag;\n "
"void main(void) {\n "
" gl_Position = projectMat * viewMat * modelMat * positionVA;\n "
" norm_frag = model3IT * normalVA;\n "
" color_frag = colorSolid;\n "
"}\n ");
static const char *AmbDiff_frag
= (VERSION "uniform vec3 lightDir;\n "
"uniform float phongKa;\n "
"uniform float phongKd;\n "
"layout(location = 0) in vec3 norm_frag;\n "
"layout(location = 1) in vec4 color_frag;\n "
"out vec4 fcol;\n "
"void main(void) {\n "
" float ldot = max(0, dot(lightDir, normalize(norm_frag)));\n "
" fcol = color_frag*(phongKa + phongKd*ldot);\n "
" fcol.a = color_frag.a;\n "
"}\n");
static const char *AmbDiff2Side_frag
= (VERSION "uniform vec3 lightDir;\n "
"uniform float phongKa;\n "
"uniform float phongKd;\n "
"layout(location = 0) in vec3 norm_frag;\n "
"layout(location = 1) in vec4 color_frag;\n "
"out vec4 fcol;\n "
"void main(void) {\n "
// here's the two-sided lighting
" float ldot = max(dot(lightDir, -normalize(norm_frag)),\n "
" dot(lightDir, normalize(norm_frag)));\n "
" fcol = color_frag*(phongKa + phongKd*ldot);\n "
" fcol.a = color_frag.a;\n "
"}\n");
static GLchar * // HEY what's the right way to do this
strdupe(const char *str) {
GLchar *ret;
ret = new GLchar[strlen(str) + 1];
strcpy(ret, str);
return ret;
}
static GLchar *fileContents(const char *fname) {
static const std::string me = "Hale::fileContents";
GLchar *ret;
FILE *file;
long len;
if (!fname) {
throw std::runtime_error(me + ": got NULL fname");
}
if (!(file = fopen(fname, "r"))) {
throw std::runtime_error(me + ": unable to open \"" + fname
+ "\": " + std::strerror(errno));
}
/* learn length of file contents */
fseek(file, 0L, SEEK_END);
len = ftell(file);
fseek(file, 0L, SEEK_SET);
ret = new GLchar[len + 1];
/* copy file into string */
fread(ret, 1, len, file);
ret[len] = '\0';
fclose(file);
return ret;
}
static GLint shaderNew(GLint shtype, const GLchar *shaderSrc) {
static const std::string me = "Hale::shaderNew";
GLuint shaderId;
GLint status;
shaderId = glCreateShader(shtype);
if (debugging) printf("# glCreateShader(%u) -> %u\n", shtype, shaderId);
glErrorCheck(me, "glCreateShader");
glShaderSource(shaderId, 1, &shaderSrc, NULL);
if (debugging) printf("# glShaderSource(%u, 1):\n%s\n", shaderId, shaderSrc);
glErrorCheck(me, "glShaderSource");
glCompileShader(shaderId);
if (debugging) printf("# glCompileShader(%u)\n", shaderId);
glErrorCheck(me, "glCompileShader");
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &status);
if (debugging)
printf("# glGetShaderiv(%u, GL_COMPILE_STATUS, &) -> %d (%s)\n", shaderId, status,
GLBOOLSTR(status));
glErrorCheck(me, "glGetShaderiv");
/* HEY why does this sometimes set status to 32767 (not 0 or 1)? */
GLint logSize;
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logSize);
char *logMsg = AIR_CALLOC(logSize + 1, char);
assert(logMsg);
/* http://gamedev.stackexchange.com/questions/30429/how-to-detect-glsl-warnings
suggests something like this to get warnings */
if (logSize > 0) {
glGetShaderInfoLog(shaderId, logSize, NULL, logMsg);
fprintf(stderr, "GLSL compiler %s:\n%s\n",
(GL_FALSE == status ? "error" : "warning"), logMsg);
}
if (GL_FALSE == status) {
throw std::runtime_error(me + ": compiler error:\n" + logMsg);
glDeleteShader(shaderId);
free(logMsg);
return 0;
}
free(logMsg);
return shaderId;
}
Program::Program(preprogram prog) {
static const std::string me = "Hale::Program::Program(prog)";
if (preprogramAmbDiff == prog || preprogramAmbDiff2Side == prog) {
_vertCode = strdupe(AmbDiff_vert);
} else if (preprogramAmbDiffSolid == prog || preprogramAmbDiff2SideSolid == prog) {
_vertCode = strdupe(AmbDiffSolid_vert);
} else {
throw std::runtime_error(me + ": prog " + std::to_string(prog)
+ " not recognized");
}
if (preprogramAmbDiff2Side == prog || preprogramAmbDiff2SideSolid == prog) {
_fragCode = strdupe(AmbDiff2Side_frag);
} else {
_fragCode = strdupe(AmbDiff_frag);
}
_vertId = 0;
_fragId = 0;
_progId = 0;
}
Program::Program(const char *vertFname, const char *fragFname) {
_vertCode = fileContents(vertFname);
_vertId = 0;
_fragCode = fileContents(fragFname);
_fragId = 0;
_progId = 0;
}
Program::~Program() {
delete _vertCode;
delete _fragCode;
// "A value of 0 for shader will be silently ignored."
glDeleteShader(_vertId);
glDeleteShader(_fragId);
// "A value of 0 for program will be silently ignored."
glDeleteProgram(_progId);
}
void Program::compile() {
static const std::string me = "Hale::Program::compile";
/* would need these if you can re-use a Hale::Program
with different shader sources
glDeleteShader(_vertId);
glDeleteShader(_fragId);
glDeleteProgram(_progId);
*/
_vertId = shaderNew(GL_VERTEX_SHADER, _vertCode);
_fragId = shaderNew(GL_FRAGMENT_SHADER, _fragCode);
_progId = glCreateProgram();
if (debugging) printf("# glCreateProgram() -> %d\n", _progId);
glErrorCheck(me, "glCreateProgram");
glAttachShader(_progId, _vertId);
if (debugging) printf("# glAttachShader(%d, %d) -> (void)\n", _progId, _vertId);
glErrorCheck(me, "glAttachShader(vertId " + std::to_string(_vertId) + ")");
glAttachShader(_progId, _fragId);
if (debugging) printf("# glAttachShader(%d, %d) -> (void)\n", _progId, _fragId);
glErrorCheck(me, "glAttachShader(fragId " + std::to_string(_fragId) + ")");
return;
}
void Program::bindAttribute(GLuint idx, const GLchar *name) {
static const std::string me = "Hale::Program::bindAttribute";
glBindAttribLocation(_progId, idx, name);
if (debugging)
printf("# glBindAttribLocation(%u, %u, %s) -> (void)\n", _progId, idx, name);
/* had hoped to use something like glGetVertexAttribiv to learn
about the type of variable "name" (to enable the kind of type
checking we support for uniforms), but those functions don't even
take a program index ... */
glErrorCheck(me, std::string("glBindAttribLocation(") + name + ")");
}
void Program::link() {
static const std::string me = "Hale::Program::use";
GLint status;
glLinkProgram(_progId);
if (debugging) printf("# glLinkProgram(%u);\n", _progId);
glGetProgramiv(_progId, GL_LINK_STATUS, &status);
if (debugging)
printf("# glGetProgramiv(%u, GL_LINK_STATUS, &) -> %d (%s);\n", _progId, status,
GLBOOLSTR(status));
if (GL_FALSE == status) {
GLint logSize;
glGetProgramiv(_progId, GL_INFO_LOG_LENGTH, &logSize);
if (logSize) {
char *logMsg = AIR_CALLOC(logSize + 1, char);
assert(logMsg);
glGetProgramInfoLog(_progId, logSize, NULL, logMsg);
throw std::runtime_error(me + ": linking error: " + logMsg);
free(logMsg);
}
throw std::runtime_error("compilation failed");
}
if (debugging) {
GLint idx;
#define GETALOC(str) \
idx = glGetAttribLocation(_progId, str); \
printf("# glGetAttribLocation(%d, \"" str "\") -> %d\n", _progId, idx);
/* these two were added for initial debugging; ideally which ones
are queried should depend on which attributes are used */
GETALOC("positionVA");
GETALOC("normalVA");
#undef GETALOC
}
/* learn uniform types (uniformType) and locations (uniformLocation) once,
so that we can re-use them during use. Based on
https://www.opengl.org/wiki/Program_Introspection */
GLint uniN, uniI, uniSize;
GLenum uniType;
char uniName[512];
uniformType.clear();
uniformLocation.clear();
glGetProgramiv(_progId, GL_ACTIVE_UNIFORMS, &uniN);
if (debugging)
printf("# glGetProgramiv(%d, GL_ACTIVE_UNIFORMS, &); -> %d; ... instrospection "
"to get uniform types ...\n",
_progId, uniN);
glErrorCheck(me, "glGetProgramiv(GL_ACTIVE_UNIFORMS)");
for (uniI = 0; uniI < uniN; uniI++) {
glGetActiveUniform(_progId, uniI, sizeof(uniName), NULL, &uniSize, &uniType,
uniName);
glErrorCheck(me, std::string("glGetActiveUniform(") + std::to_string(uniI) + ")");
uniformType[uniName] = glEnumDesc[uniType];
GLint uniLoc = glGetUniformLocation(_progId, uniName);
glErrorCheck(me, std::string("glGetUniformLocation(") + uniName + ")");
if (-1 == uniLoc) {
throw std::runtime_error(me + ": \"" + uniName
+ "\" is not a known uniform name");
}
uniformLocation[uniName] = uniLoc;
if (debugging)
printf("!%s: uniform[%d]: \"%s\": type %s size %d location %d\n", me.c_str(),
uniI, uniName, uniformType[uniName].enumStr.c_str(), uniSize,
uniformLocation[uniName]);
}
return;
}
void Program::use() const {
static const std::string me = "Hale::Program::use";
if (Hale::_programCurrent == this) {
/* we're already using this program; nothing to do here */
return;
}
glUseProgram(_progId);
if (debugging) printf("# glUseProgram(%u)\n", _progId);
glErrorCheck(me, "glUseProgram(" + std::to_string(_progId) + ")");
/* set global Program pointer to us */
Hale::_programCurrent = this;
/* re-set the sticky uniforms */
stickyUniform();
return;
}
GLuint Program::progId() const { return _progId; }
/* ------------------------------------------------------------ */
// HEY: what's right way to avoid copy+paste?
void uniform(std::string name, float vv, bool sticky) {
if (_programCurrent) {
_programCurrent->uniform(name, vv, sticky);
}
}
void Program::uniform(std::string name, float vv, bool sticky) const {
static const std::string me = "Program::uniform";
auto iter = uniformType.find(name);
if (uniformType.end() == iter) {
throw std::runtime_error(me + ": \"" + name + "\" is not an active uniform");
}
glEnumItem ii = iter->second;
if (GL_FLOAT != ii.enumVal) {
throw std::runtime_error(me + ": \"" + name + "\" is a " + ii.glslStr
+ " but got a float");
}
glUniform1f(uniformLocation.at(name), vv);
glErrorCheck(me, std::string("glUniform1f(") + name + ")");
if (debugging) {
printf("# glUniform1f(%u, %f);\n", uniformLocation.at(name), vv);
}
if (sticky) {
stickyUniformFloat[name] = vv;
}
}
// HEY: what's right way to avoid copy+paste?
void uniform(std::string name, glm::vec3 vv, bool sticky) {
if (_programCurrent) {
_programCurrent->uniform(name, vv, sticky);
}
}
void Program::uniform(std::string name, glm::vec3 vv, bool sticky) const {
static const std::string me = "Program::uniform";
auto iter = uniformType.find(name);
if (uniformType.end() == iter) {
throw std::runtime_error(me + ": \"" + name + "\" is not an active uniform");
}
glEnumItem ii = iter->second;
if (GL_FLOAT_VEC3 != ii.enumVal) {
throw std::runtime_error(me + ": \"" + name + "\" is a " + ii.glslStr
+ " but got a vec3");
}
glUniform3fv(uniformLocation.at(name), 1, glm::value_ptr(vv));
glErrorCheck(me, std::string("glUniform3fv(") + name + ")");
if (debugging) {
printf("# glUniform3fv(%u, 1, %s);\n", uniformLocation.at(name),
glm::to_string(vv).c_str());
}
if (sticky) {
stickyUniformVec3[name] = vv;
}
}
// HEY: what's right way to avoid copy+paste?
void uniform(std::string name, glm::vec4 vv, bool sticky) {
if (_programCurrent) {
_programCurrent->uniform(name, vv, sticky);
}
}
void Program::uniform(std::string name, glm::vec4 vv, bool sticky) const {
static const std::string me = "Program::uniform";
auto iter = uniformType.find(name);
if (uniformType.end() == iter) {
throw std::runtime_error(me + ": \"" + name + "\" is not an active uniform");
}
glEnumItem ii = iter->second;
if (GL_FLOAT_VEC4 != ii.enumVal) {
throw std::runtime_error(me + ": \"" + name + "\" is a " + ii.glslStr
+ " but got a vec4");
}
glUniform4fv(uniformLocation.at(name), 1, glm::value_ptr(vv));
glErrorCheck(me, std::string("glUniform4fv(") + name + ")");
if (debugging) {
printf("# glUniform4fv(%u, 1, %s);\n", uniformLocation.at(name),
glm::to_string(vv).c_str());
}
if (sticky) {
stickyUniformVec4[name] = vv;
}
}
// HEY: what's right way to avoid copy+paste?
void uniform(std::string name, glm::mat3 vv, bool sticky) {
if (_programCurrent) {
_programCurrent->uniform(name, vv, sticky);
}
}
void Program::uniform(std::string name, glm::mat3 vv, bool sticky) const {
static const std::string me = "Program::uniform";
auto iter = uniformType.find(name);
if (uniformType.end() == iter) {
throw std::runtime_error(me + ": \"" + name + "\" is not an active uniform");
}
glEnumItem ii = iter->second;
if (GL_FLOAT_MAT3 != ii.enumVal) {
throw std::runtime_error(me + ": \"" + name + "\" is a " + ii.glslStr
+ " but got a mat4");
}
glUniformMatrix3fv(uniformLocation.at(name), 1, 0, glm::value_ptr(vv));
glErrorCheck(me, std::string("glUniformMatrix3fv(") + name + ")");
if (debugging) {
printf("# glUniformMatrix3fv(%u, 1, 0, %s);\n", uniformLocation.at(name),
glm::to_string(vv).c_str());
}
if (sticky) {
stickyUniformMat3[name] = vv;
}
}
// HEY: what's right way to avoid copy+paste?
void uniform(std::string name, glm::mat4 vv, bool sticky) {
if (_programCurrent) {
_programCurrent->uniform(name, vv, sticky);
}
}
void Program::uniform(std::string name, glm::mat4 vv, bool sticky) const {
static const std::string me = "Program::uniform";
auto iter = uniformType.find(name);
if (uniformType.end() == iter) {
throw std::runtime_error(me + ": \"" + name + "\" is not an active uniform");
}
glEnumItem ii = iter->second;
if (GL_FLOAT_MAT4 != ii.enumVal) {
throw std::runtime_error(me + ": \"" + name + "\" is a " + ii.glslStr
+ " but got a mat4");
}
glUniformMatrix4fv(uniformLocation.at(name), 1, 0, glm::value_ptr(vv));
glErrorCheck(me, std::string("glUniformMatrix4fv(") + name + ")");
if (debugging) {
printf("# glUniformMatrix4fv(%u, 1, 0, %s);\n", uniformLocation.at(name),
glm::to_string(vv).c_str());
}
if (sticky) {
stickyUniformMat4[name] = vv;
}
}
/* ------------------------------------------------------------ */
/* HEY: there's currently no way to unstick a sticky uniform; perhaps there
needs to be a new "unstick" argument to the uniform() calls, or the
"sticky" argument can have 1 of 3 values: "true", "false", or "unstick" */
void stickyUniform(void) {
for (auto si = stickyUniformFloat.begin(); si != stickyUniformFloat.end(); si++) {
Hale::uniform(si->first, si->second);
}
for (auto si = stickyUniformVec3.begin(); si != stickyUniformVec3.end(); si++) {
Hale::uniform(si->first, si->second);
}
for (auto si = stickyUniformVec4.begin(); si != stickyUniformVec4.end(); si++) {
Hale::uniform(si->first, si->second);
}
for (auto si = stickyUniformMat3.begin(); si != stickyUniformMat3.end(); si++) {
Hale::uniform(si->first, si->second);
}
for (auto si = stickyUniformMat4.begin(); si != stickyUniformMat4.end(); si++) {
Hale::uniform(si->first, si->second);
}
}
/* ------------------------------------------------------------ */
const Program *ProgramLib(preprogram pp) {
static const std::string me = "Hale::ProgramLib";
if (!(preprogramUnknown < pp && pp < preprogramLast)) {
throw std::runtime_error(me + ": prog " + std::to_string(pp) + " not valid");
}
if (_program[pp]) {
/* this preprogram has already been compiled; re-use */
if (debugging)
printf("!%s: re-using pre-compiled %d (GL %u)\n", me.c_str(), pp,
_program[pp]->progId());
return _program[pp];
}
Program *prog = new Program(pp);
prog->compile();
switch (pp) {
case preprogramAmbDiff:
case preprogramAmbDiff2Side:
prog->bindAttribute(Hale::vertAttrIdxXYZW, "positionVA");
prog->bindAttribute(Hale::vertAttrIdxRGBA, "colorVA");
prog->bindAttribute(Hale::vertAttrIdxNorm, "normalVA"); // HEY Tex2, Tang
break;
case preprogramAmbDiffSolid:
case preprogramAmbDiff2SideSolid:
prog->bindAttribute(Hale::vertAttrIdxXYZW, "positionVA");
prog->bindAttribute(Hale::vertAttrIdxNorm, "normalVA"); // HEY Tex2, Tang
break;
default:
throw std::runtime_error(me + ": sorry, prog " + std::to_string(pp)
+ " not implemented");
break;
}
prog->link();
_program[pp] = prog;
return prog;
}
} // namespace Hale