summaryrefslogtreecommitdiffstats
path: root/progs/glsl/shtest.c
blob: 97f6f9f8a443125e2735fc2fb11096cf4a182609 (plain)
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
 * Simple shader test harness.
 * Brian Paul
 * 13 Aug 2009
 *
 * Usage:
 *   shtest --vs vertShaderFile --fs fragShaderFile
 *
 *   In this case the given vertex/frag shaders are read and compiled.
 *   Random values are assigned to the uniforms.
 *
 * or:
 *   shtest configFile
 *
 *   In this case a config file is read that specifies the file names
 *   of the shaders plus initial values for uniforms.
 *
 * Example config file:
 *
 * vs shader.vert
 * fs shader.frag
 * uniform pi 3.14159
 * uniform v1 1.0 0.5 0.2 0.3
 *
 */


#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <GL/glew.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include "shaderutil.h"
#include "readtex.h"


typedef enum
{
   SPHERE,
   CUBE,
   NUM_SHAPES
} shape;


static char *FragShaderFile = NULL;
static char *VertShaderFile = NULL;
static char *ConfigFile = NULL;

/* program/shader objects */
static GLuint fragShader;
static GLuint vertShader;
static GLuint Program;


#define MAX_UNIFORMS 100
static struct uniform_info Uniforms[MAX_UNIFORMS];
static GLuint NumUniforms = 0;


#define MAX_ATTRIBS 100
static struct attrib_info Attribs[MAX_ATTRIBS];
static GLuint NumAttribs = 0;


/**
 * Config file info.
 */
struct config_file
{
   struct name_value
   {
      char name[100];
      float value[4];
      int type;
   } uniforms[100];

   int num_uniforms;
};


static GLint win = 0;
static GLboolean Anim = GL_FALSE;
static GLfloat TexRot = 0.0;
static GLfloat xRot = 0.0f, yRot = 0.0f, zRot = 0.0f;
static shape Object = SPHERE;


static float
RandomFloat(float min, float max)
{
   int k = rand() % 10000;
   float x = min + (max - min) * k / 10000.0;
   return x;
}


/** Set new random values for uniforms */
static void
RandomUniformValues(void)
{
   GLuint i;
   for (i = 0; i < NumUniforms; i++) {
      if (Uniforms[i].type == GL_FLOAT) {
         Uniforms[i].value[0] = RandomFloat(0.0, 1.0);
      }
      else {
         Uniforms[i].value[0] = RandomFloat(-1.0, 2.0);
         Uniforms[i].value[1] = RandomFloat(-1.0, 2.0);
         Uniforms[i].value[2] = RandomFloat(-1.0, 2.0);
         Uniforms[i].value[3] = RandomFloat(-1.0, 2.0);
      }
   }
}


static void
Idle(void)
{
   yRot += 2.0;
   if (yRot > 360.0)
      yRot -= 360.0;
   glutPostRedisplay();
}



static void
SquareVertex(GLfloat s, GLfloat t, GLfloat size)
{
   GLfloat x = -size + s * 2.0 * size;
   GLfloat y = -size + t * 2.0 * size;
   GLuint i;

   glMultiTexCoord2f(GL_TEXTURE0, s, t);
   glMultiTexCoord2f(GL_TEXTURE1, s, t);
   glMultiTexCoord2f(GL_TEXTURE2, s, t);
   glMultiTexCoord2f(GL_TEXTURE3, s, t);

   /* assign (s,t) to the generic attributes */
   for (i = 0; i < NumAttribs; i++) {
      if (Attribs[i].location >= 0) {
         glVertexAttrib2f(Attribs[i].location, s, t);
      }
   }

   glVertex2f(x, y);
}


/*
 * Draw a square, specifying normal and tangent vectors.
 */
static void
Square(GLfloat size)
{
   GLint tangentAttrib = 1;
   glNormal3f(0, 0, 1);
   glVertexAttrib3f(tangentAttrib, 1, 0, 0);
   glBegin(GL_POLYGON);
#if 1
   SquareVertex(0, 0, size);
   SquareVertex(1, 0, size);
   SquareVertex(1, 1, size);
   SquareVertex(0, 1, size);
#else
   glTexCoord2f(0, 0);  glVertex2f(-size, -size);
   glTexCoord2f(1, 0);  glVertex2f( size, -size);
   glTexCoord2f(1, 1);  glVertex2f( size,  size);
   glTexCoord2f(0, 1);  glVertex2f(-size,  size);
#endif
   glEnd();
}


static void
Cube(GLfloat size)
{
   /* +X */
   glPushMatrix();
   glRotatef(90, 0, 1, 0);
   glTranslatef(0, 0, size);
   Square(size);
   glPopMatrix();

   /* -X */
   glPushMatrix();
   glRotatef(-90, 0, 1, 0);
   glTranslatef(0, 0, size);
   Square(size);
   glPopMatrix();

   /* +Y */
   glPushMatrix();
   glRotatef(90, 1, 0, 0);
   glTranslatef(0, 0, size);
   Square(size);
   glPopMatrix();

   /* -Y */
   glPushMatrix();
   glRotatef(-90, 1, 0, 0);
   glTranslatef(0, 0, size);
   Square(size);
   glPopMatrix();


   /* +Z */
   glPushMatrix();
   glTranslatef(0, 0, size);
   Square(size);
   glPopMatrix();

   /* -Z */
   glPushMatrix();
   glRotatef(180, 0, 1, 0);
   glTranslatef(0, 0, size);
   Square(size);
   glPopMatrix();
}


static void
Sphere(GLfloat radius, GLint slices, GLint stacks)
{
   static GLUquadricObj *q = NULL;

   if (!q) {
      q = gluNewQuadric();
      gluQuadricDrawStyle(q, GLU_FILL);
      gluQuadricNormals(q, GLU_SMOOTH);
      gluQuadricTexture(q, GL_TRUE);
   }

   gluSphere(q, radius, slices, stacks);
}


static void
Redisplay(void)
{
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
   glPushMatrix();
   glRotatef(xRot, 1.0f, 0.0f, 0.0f);
   glRotatef(yRot, 0.0f, 1.0f, 0.0f);
   glRotatef(zRot, 0.0f, 0.0f, 1.0f);

   glMatrixMode(GL_TEXTURE);
   glLoadIdentity();
   glRotatef(TexRot, 0.0f, 1.0f, 0.0f);
   glMatrixMode(GL_MODELVIEW);

   if (Object == SPHERE) {
      Sphere(2.0, 20, 10);
   }
   else if (Object == CUBE) {
      Cube(2.0);
   }

   glPopMatrix();

   glutSwapBuffers();
}


static void
Reshape(int width, int height)
{
   glViewport(0, 0, width, height);
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glFrustum(-1.0, 1.0, -1.0, 1.0, 5.0, 25.0);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glTranslatef(0.0f, 0.0f, -15.0f);
}


static void
CleanUp(void)
{
   glDeleteShader(fragShader);
   glDeleteShader(vertShader);
   glDeleteProgram(Program);
   glutDestroyWindow(win);
}


static void
Key(unsigned char key, int x, int y)
{
   const GLfloat step = 2.0;
  (void) x;
  (void) y;

   switch(key) {
   case 'a':
      Anim = !Anim;
      if (Anim)
         glutIdleFunc(Idle);
      else
         glutIdleFunc(NULL);
      break;
   case 'z':
      zRot += step;
      break;
   case 'Z':
      zRot -= step;
      break;
   case 'o':
      Object = (Object + 1) % NUM_SHAPES;
      break;
   case 'r':
      RandomUniformValues();
      SetUniformValues(Program, Uniforms);
      PrintUniforms(Uniforms);
      break;
   case 27:
      CleanUp();
      exit(0);
      break;
   }
   glutPostRedisplay();
}


static void
SpecialKey(int key, int x, int y)
{
   const GLfloat step = 2.0;

  (void) x;
  (void) y;

   switch(key) {
   case GLUT_KEY_UP:
      xRot += step;
      break;
   case GLUT_KEY_DOWN:
      xRot -= step;
      break;
   case GLUT_KEY_LEFT:
      yRot -= step;
      break;
   case GLUT_KEY_RIGHT:
      yRot += step;
      break;
   }
   glutPostRedisplay();
}


static void
InitUniforms(const struct config_file *conf,
             struct uniform_info uniforms[])
{
   int i;

   for (i = 0; i < conf->num_uniforms; i++) {
      int j;
      for (j = 0; uniforms[j].name; j++) {
         if (strcmp(uniforms[j].name, conf->uniforms[i].name) == 0) {
            uniforms[j].type = conf->uniforms[i].type;
            uniforms[j].value[0] = conf->uniforms[i].value[0];
            uniforms[j].value[1] = conf->uniforms[i].value[1];
            uniforms[j].value[2] = conf->uniforms[i].value[2];
            uniforms[j].value[3] = conf->uniforms[i].value[3];
         }
      }
   }
}


static void
LoadTexture(GLint unit, const char *texFileName)
{
   GLint imgWidth, imgHeight;
   GLenum imgFormat;
   GLubyte *image = NULL;
   GLuint tex;
   GLenum filter = GL_LINEAR;

   image = LoadRGBImage(texFileName, &imgWidth, &imgHeight, &imgFormat);
   if (!image) {
      printf("Couldn't read %s\n", texFileName);
      exit(1);
   }

   printf("Load Texture: unit %d: %s %d x %d\n",
          unit, texFileName, imgWidth, imgHeight);

   glActiveTexture(GL_TEXTURE0 + unit);
   glGenTextures(1, &tex);
   glBindTexture(GL_TEXTURE_2D, tex);

   gluBuild2DMipmaps(GL_TEXTURE_2D, 4, imgWidth, imgHeight,
                     imgFormat, GL_UNSIGNED_BYTE, image);
   free(image);
      
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
}


static GLenum
TypeFromName(const char *n)
{
   static const struct {
      const char *name;
      GLenum type;
   } types[] = {
      { "GL_FLOAT", GL_FLOAT },
      { "GL_FLOAT_VEC2", GL_FLOAT_VEC2 },
      { "GL_FLOAT_VEC3", GL_FLOAT_VEC3 },
      { "GL_FLOAT_VEC4", GL_FLOAT_VEC4 },
      { "GL_INT", GL_INT },
      { "GL_INT_VEC2", GL_INT_VEC2 },
      { "GL_INT_VEC3", GL_INT_VEC3 },
      { "GL_INT_VEC4", GL_INT_VEC4 },
      { "GL_SAMPLER_2D", GL_SAMPLER_2D },
      { NULL, 0 }
   };
   GLuint i;

   for (i = 0; types[i].name; i++) {
      if (strcmp(types[i].name, n) == 0)
         return types[i].type;
   }
   abort();
   return GL_NONE;
}



/**
 * Read a config file.
 */
static void
ReadConfigFile(const char *filename, struct config_file *conf)
{
   char line[1000];
   FILE *f;

   f = fopen(filename, "r");
   if (!f) {
      fprintf(stderr, "Unable to open config file %s\n", filename);
      exit(1);
   }

   conf->num_uniforms = 0;

   /* ugly but functional parser */
   while (!feof(f)) {
      fgets(line, sizeof(line), f);
      if (!feof(f) && line[0]) {
         if (strncmp(line, "vs ", 3) == 0) {
            VertShaderFile = strdup(line + 3);
            VertShaderFile[strlen(VertShaderFile) - 1] = 0;
         }
         else if (strncmp(line, "fs ", 3) == 0) {
            FragShaderFile = strdup(line + 3);
            FragShaderFile[strlen(FragShaderFile) - 1] = 0;
         }
         else if (strncmp(line, "texture ", 8) == 0) {
            char texFileName[100];
            int unit, k;
            k = sscanf(line + 8, "%d %s", &unit, texFileName);
            assert(k == 2);
            LoadTexture(unit, texFileName);
         }
         else if (strncmp(line, "uniform ", 8) == 0) {
            char name[1000], typeName[100];
            int k;
            float v1 = 0.0F, v2 = 0.0F, v3 = 0.0F, v4 = 0.0F;
            GLenum type;

            k = sscanf(line + 8, "%s %s %f %f %f %f", name, typeName,
                       &v1, &v2, &v3, &v4);

            type = TypeFromName(typeName);

            strcpy(conf->uniforms[conf->num_uniforms].name, name);
            conf->uniforms[conf->num_uniforms].value[0] = v1;
            conf->uniforms[conf->num_uniforms].value[1] = v2;
            conf->uniforms[conf->num_uniforms].value[2] = v3;
            conf->uniforms[conf->num_uniforms].value[3] = v4;
            conf->uniforms[conf->num_uniforms].type = type;
            conf->num_uniforms++;
         }
         else {
            if (strlen(line) > 1) {
               fprintf(stderr, "syntax error in: %s\n", line);
               break;
            }
         }
      }
   }

   fclose(f);
}


static void
Init(void)
{
   struct config_file config;
   memset(&config, 0, sizeof(config));

   if (ConfigFile)
      ReadConfigFile(ConfigFile, &config);

   if (!VertShaderFile) {
      fprintf(stderr, "Error: no vertex shader\n");
      exit(1);
   }

   if (!FragShaderFile) {
      fprintf(stderr, "Error: no fragment shader\n");
      exit(1);
   }

   if (!ShadersSupported())
      exit(1);

   vertShader = CompileShaderFile(GL_VERTEX_SHADER, VertShaderFile);
   fragShader = CompileShaderFile(GL_FRAGMENT_SHADER, FragShaderFile);
   Program = LinkShaders(vertShader, fragShader);

   glUseProgram(Program);

   NumUniforms = GetUniforms(Program, Uniforms);
   if (config.num_uniforms) {
      InitUniforms(&config, Uniforms);
   }
   else {
      RandomUniformValues();
   }
   SetUniformValues(Program, Uniforms);
   PrintUniforms(Uniforms);

   NumAttribs = GetAttribs(Program, Attribs);
   PrintAttribs(Attribs);

   //assert(glGetError() == 0);

   glClearColor(0.4f, 0.4f, 0.8f, 0.0f);

   glEnable(GL_DEPTH_TEST);

   glColor3f(1, 0, 0);
}


static void
Keys(void)
{
   printf("Keyboard:\n");
   printf("       a  Animation toggle\n");
   printf("       r  Randomize uniform values\n");
   printf("       o  Change object\n");
   printf("  arrows  Rotate object\n");
   printf("     ESC  Exit\n");
}


static void
Usage(void)
{
   printf("Usage:\n");
   printf("   shtest config.shtest\n");
   printf("       Run w/ given config file.\n");
   printf("   shtest --vs vertShader --fs fragShader\n");
   printf("       Load/compile given shaders.\n");
}


static void
ParseOptions(int argc, char *argv[])
{
   int i;

   if (argc == 1) {
      Usage();
      exit(1);
   }

   for (i = 1; i < argc; i++) {
      if (strcmp(argv[i], "--fs") == 0) {
         FragShaderFile = argv[i+1];
         i++;
      }
      else if (strcmp(argv[i], "--vs") == 0) {
         VertShaderFile = argv[i+1];
         i++;
      }
      else {
         /* assume the arg is a config file */
         ConfigFile = argv[i];
         break;
      }
   }
}


int
main(int argc, char *argv[])
{
   glutInit(&argc, argv);
   glutInitWindowPosition( 0, 0);
   glutInitWindowSize(400, 400);
   glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
   win = glutCreateWindow(argv[0]);
   glewInit();
   glutReshapeFunc(Reshape);
   glutKeyboardFunc(Key);
   glutSpecialFunc(SpecialKey);
   glutDisplayFunc(Redisplay);
   ParseOptions(argc, argv);
   Init();
   Keys();
   glutMainLoop();
   return 0;
}