merge from master
[mesa.git] / progs / glsl / texdemo1.c
1 /**
2 * Test texturing with GL shading language.
3 *
4 * Copyright (C) 2007 Brian Paul All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
20 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24
25
26 #include <assert.h>
27 #include <math.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include "GL/glut.h"
32 #include "readtex.h"
33 #include "extfuncs.h"
34
35 static const char *Demo = "texdemo1";
36
37 static const char *ReflectVertFile = "reflect.vert.txt";
38 static const char *CubeFragFile = "cubemap.frag.txt";
39
40 static const char *SimpleVertFile = "simple.vert.txt";
41 static const char *SimpleTexFragFile = "shadowtex.frag.txt";
42
43 static const char *GroundImage = "../images/tile.rgb";
44
45 static GLuint Program1, Program2;
46
47 static GLfloat TexXrot = 0, TexYrot = 0;
48 static GLfloat Xrot = 20.0, Yrot = 20.0, Zrot = 0.0;
49 static GLfloat EyeDist = 10;
50 static GLboolean Anim = GL_TRUE;
51
52
53 struct uniform_info {
54 const char *name;
55 GLuint size;
56 GLint location;
57 GLenum type; /**< GL_FLOAT or GL_INT */
58 GLfloat value[4];
59 };
60
61 static struct uniform_info ReflectUniforms[] = {
62 { "cubeTex", 1, -1, GL_INT, { 0, 0, 0, 0 } },
63 { "lightPos", 3, -1, GL_FLOAT, { 10, 10, 20, 0 } },
64 { NULL, 0, 0, 0, { 0, 0, 0, 0 } }
65 };
66
67 static struct uniform_info SimpleUniforms[] = {
68 { "tex2d", 1, -1, GL_INT, { 1, 0, 0, 0 } },
69 { "lightPos", 3, -1, GL_FLOAT, { 10, 10, 20, 0 } },
70 { NULL, 0, 0, 0, { 0, 0, 0, 0 } }
71 };
72
73
74 static void
75 CheckError(int line)
76 {
77 GLenum err = glGetError();
78 if (err) {
79 printf("GL Error %s (0x%x) at line %d\n",
80 gluErrorString(err), (int) err, line);
81 }
82 }
83
84
85 static void
86 DrawGround(GLfloat size)
87 {
88 glPushMatrix();
89 glRotatef(90, 1, 0, 0);
90 glNormal3f(0, 0, 1);
91 glBegin(GL_POLYGON);
92 glTexCoord2f(-2, -2); glVertex2f(-size, -size);
93 glTexCoord2f( 2, -2); glVertex2f( size, -size);
94 glTexCoord2f( 2, 2); glVertex2f( size, size);
95 glTexCoord2f(-2, 2); glVertex2f(-size, size);
96 glEnd();
97 glPopMatrix();
98 }
99
100
101 static void
102 draw(void)
103 {
104 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
105
106 glEnable(GL_TEXTURE_2D);
107
108 glPushMatrix(); /* modelview matrix */
109 glTranslatef(0.0, 0.0, -EyeDist);
110 glRotatef(Xrot, 1, 0, 0);
111 glRotatef(Yrot, 0, 1, 0);
112 glRotatef(Zrot, 0, 0, 1);
113
114 /* sphere w/ reflection map */
115 glPushMatrix();
116 glTranslatef(0, 1, 0);
117 glUseProgram_func(Program1);
118
119 /* setup texture matrix */
120 glActiveTexture(GL_TEXTURE0);
121 glMatrixMode(GL_TEXTURE);
122 glLoadIdentity();
123 glRotatef(-TexYrot, 0, 1, 0);
124 glRotatef(-TexXrot, 1, 0, 0);
125
126 glEnable(GL_TEXTURE_GEN_S);
127 glEnable(GL_TEXTURE_GEN_T);
128 glEnable(GL_TEXTURE_GEN_R);
129 glutSolidSphere(2.0, 20, 20);
130
131 glLoadIdentity(); /* texture matrix */
132 glMatrixMode(GL_MODELVIEW);
133 glPopMatrix();
134
135 /* ground */
136 glUseProgram_func(Program2);
137 glTranslatef(0, -1.0, 0);
138 DrawGround(5);
139
140 glPopMatrix();
141
142 glutSwapBuffers();
143 }
144
145
146 static void
147 idle(void)
148 {
149 GLfloat t = 0.05 * glutGet(GLUT_ELAPSED_TIME);
150 TexYrot = t;
151 glutPostRedisplay();
152 }
153
154
155 static void
156 key(unsigned char k, int x, int y)
157 {
158 (void) x;
159 (void) y;
160 switch (k) {
161 case ' ':
162 case 'a':
163 Anim = !Anim;
164 if (Anim)
165 glutIdleFunc(idle);
166 else
167 glutIdleFunc(NULL);
168 break;
169 case 'z':
170 EyeDist -= 0.5;
171 if (EyeDist < 6.0)
172 EyeDist = 6.0;
173 break;
174 case 'Z':
175 EyeDist += 0.5;
176 if (EyeDist > 90.0)
177 EyeDist = 90;
178 break;
179 case 27:
180 exit(0);
181 }
182 glutPostRedisplay();
183 }
184
185
186 static void
187 specialkey(int key, int x, int y)
188 {
189 GLfloat step = 2.0;
190 (void) x;
191 (void) y;
192 switch (key) {
193 case GLUT_KEY_UP:
194 Xrot += step;
195 break;
196 case GLUT_KEY_DOWN:
197 Xrot -= step;
198 break;
199 case GLUT_KEY_LEFT:
200 Yrot -= step;
201 break;
202 case GLUT_KEY_RIGHT:
203 Yrot += step;
204 break;
205 }
206 glutPostRedisplay();
207 }
208
209
210 /* new window size or exposure */
211 static void
212 Reshape(int width, int height)
213 {
214 GLfloat ar = (float) width / (float) height;
215 glViewport(0, 0, (GLint)width, (GLint)height);
216 glMatrixMode(GL_PROJECTION);
217 glLoadIdentity();
218 glFrustum(-2.0*ar, 2.0*ar, -2.0, 2.0, 4.0, 100.0);
219 glMatrixMode(GL_MODELVIEW);
220 glLoadIdentity();
221 }
222
223
224 static void
225 InitCheckers(void)
226 {
227 #define CUBE_TEX_SIZE 64
228 GLubyte image[CUBE_TEX_SIZE][CUBE_TEX_SIZE][3];
229 static const GLubyte colors[6][3] = {
230 { 255, 0, 0 }, /* face 0 - red */
231 { 0, 255, 255 }, /* face 1 - cyan */
232 { 0, 255, 0 }, /* face 2 - green */
233 { 255, 0, 255 }, /* face 3 - purple */
234 { 0, 0, 255 }, /* face 4 - blue */
235 { 255, 255, 0 } /* face 5 - yellow */
236 };
237 static const GLenum targets[6] = {
238 GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
239 GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB,
240 GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB,
241 GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB,
242 GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB,
243 GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB
244 };
245
246 GLint i, j, f;
247
248 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
249
250 /* make colored checkerboard cube faces */
251 for (f = 0; f < 6; f++) {
252 for (i = 0; i < CUBE_TEX_SIZE; i++) {
253 for (j = 0; j < CUBE_TEX_SIZE; j++) {
254 if ((i/4 + j/4) & 1) {
255 image[i][j][0] = colors[f][0];
256 image[i][j][1] = colors[f][1];
257 image[i][j][2] = colors[f][2];
258 }
259 else {
260 image[i][j][0] = 255;
261 image[i][j][1] = 255;
262 image[i][j][2] = 255;
263 }
264 }
265 }
266
267 glTexImage2D(targets[f], 0, GL_RGB, CUBE_TEX_SIZE, CUBE_TEX_SIZE, 0,
268 GL_RGB, GL_UNSIGNED_BYTE, image);
269 }
270 }
271
272
273 static void
274 LoadFace(GLenum target, const char *filename,
275 GLboolean flipTB, GLboolean flipLR)
276 {
277 GLint w, h;
278 GLenum format;
279 GLubyte *img = LoadRGBImage(filename, &w, &h, &format);
280 if (!img) {
281 printf("Error: couldn't load texture image %s\n", filename);
282 exit(1);
283 }
284 assert(format == GL_RGB);
285
286 /* <sigh> the way the texture cube mapping works, we have to flip
287 * images to make things look right.
288 */
289 if (flipTB) {
290 const int stride = 3 * w;
291 GLubyte temp[3*1024];
292 int i;
293 for (i = 0; i < h / 2; i++) {
294 memcpy(temp, img + i * stride, stride);
295 memcpy(img + i * stride, img + (h - i - 1) * stride, stride);
296 memcpy(img + (h - i - 1) * stride, temp, stride);
297 }
298 }
299 if (flipLR) {
300 const int stride = 3 * w;
301 GLubyte temp[3];
302 GLubyte *row;
303 int i, j;
304 for (i = 0; i < h; i++) {
305 row = img + i * stride;
306 for (j = 0; j < w / 2; j++) {
307 int k = w - j - 1;
308 temp[0] = row[j*3+0];
309 temp[1] = row[j*3+1];
310 temp[2] = row[j*3+2];
311 row[j*3+0] = row[k*3+0];
312 row[j*3+1] = row[k*3+1];
313 row[j*3+2] = row[k*3+2];
314 row[k*3+0] = temp[0];
315 row[k*3+1] = temp[1];
316 row[k*3+2] = temp[2];
317 }
318 }
319 }
320
321 gluBuild2DMipmaps(target, GL_RGB, w, h, format, GL_UNSIGNED_BYTE, img);
322 free(img);
323 }
324
325
326 static void
327 LoadEnvmaps(void)
328 {
329 LoadFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB, "right.rgb", GL_TRUE, GL_FALSE);
330 LoadFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB, "left.rgb", GL_TRUE, GL_FALSE);
331 LoadFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB, "top.rgb", GL_FALSE, GL_TRUE);
332 LoadFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB, "bottom.rgb", GL_FALSE, GL_TRUE);
333 LoadFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB, "front.rgb", GL_TRUE, GL_FALSE);
334 LoadFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB, "back.rgb", GL_TRUE, GL_FALSE);
335 }
336
337
338 static void
339 InitTextures(GLboolean useImageFiles)
340 {
341 GLenum filter;
342
343 /*
344 * Env map
345 */
346 glActiveTexture(GL_TEXTURE0);
347 glBindTexture(GL_TEXTURE_CUBE_MAP, 1);
348 if (useImageFiles) {
349 LoadEnvmaps();
350 filter = GL_LINEAR;
351 }
352 else {
353 InitCheckers();
354 filter = GL_NEAREST;
355 }
356 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, filter);
357 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, filter);
358 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
359 glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
360
361 /*
362 * Ground texture
363 */
364 {
365 GLint imgWidth, imgHeight;
366 GLenum imgFormat;
367 GLubyte *image = NULL;
368
369 image = LoadRGBImage(GroundImage, &imgWidth, &imgHeight, &imgFormat);
370 if (!image) {
371 printf("Couldn't read %s\n", GroundImage);
372 exit(0);
373 }
374
375 glActiveTexture(GL_TEXTURE1);
376 glBindTexture(GL_TEXTURE_2D, 2);
377 gluBuild2DMipmaps(GL_TEXTURE_2D, 3, imgWidth, imgHeight,
378 imgFormat, GL_UNSIGNED_BYTE, image);
379 free(image);
380
381 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
382 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
383 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
384 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
385 }
386 }
387
388
389 static void
390 LoadAndCompileShader(GLuint shader, const char *text)
391 {
392 GLint stat;
393
394 glShaderSource_func(shader, 1, (const GLchar **) &text, NULL);
395
396 glCompileShader_func(shader);
397
398 glGetShaderiv_func(shader, GL_COMPILE_STATUS, &stat);
399 if (!stat) {
400 GLchar log[1000];
401 GLsizei len;
402 glGetShaderInfoLog_func(shader, 1000, &len, log);
403 fprintf(stderr, "%s: problem compiling shader: %s\n", Demo, log);
404 exit(1);
405 }
406 else {
407 printf("Shader compiled OK\n");
408 }
409 }
410
411
412 /**
413 * Read a shader from a file.
414 */
415 static void
416 ReadShader(GLuint shader, const char *filename)
417 {
418 const int max = 100*1000;
419 int n;
420 char *buffer = (char*) malloc(max);
421 FILE *f = fopen(filename, "r");
422 if (!f) {
423 fprintf(stderr, "%s: Unable to open shader file %s\n", Demo, filename);
424 exit(1);
425 }
426
427 n = fread(buffer, 1, max, f);
428 printf("%s: read %d bytes from shader file %s\n", Demo, n, filename);
429 if (n > 0) {
430 buffer[n] = 0;
431 LoadAndCompileShader(shader, buffer);
432 }
433
434 fclose(f);
435 free(buffer);
436 }
437
438
439 static void
440 CheckLink(GLuint prog)
441 {
442 GLint stat;
443 glGetProgramiv_func(prog, GL_LINK_STATUS, &stat);
444 if (!stat) {
445 GLchar log[1000];
446 GLsizei len;
447 glGetProgramInfoLog_func(prog, 1000, &len, log);
448 fprintf(stderr, "Linker error:\n%s\n", log);
449 }
450 else {
451 fprintf(stderr, "Link success!\n");
452 }
453 }
454
455
456 static GLuint
457 CreateProgram(const char *vertProgFile, const char *fragProgFile,
458 struct uniform_info *uniforms)
459 {
460 GLuint fragShader = 0, vertShader = 0, program = 0;
461 GLint i;
462
463 program = glCreateProgram_func();
464 if (vertProgFile) {
465 vertShader = glCreateShader_func(GL_VERTEX_SHADER);
466 ReadShader(vertShader, vertProgFile);
467 glAttachShader_func(program, vertShader);
468 }
469
470 if (fragProgFile) {
471 fragShader = glCreateShader_func(GL_FRAGMENT_SHADER);
472 ReadShader(fragShader, fragProgFile);
473 glAttachShader_func(program, fragShader);
474 }
475
476 glLinkProgram_func(program);
477 CheckLink(program);
478
479 glUseProgram_func(program);
480
481 assert(glIsProgram_func(program));
482 assert(glIsShader_func(fragShader));
483 assert(glIsShader_func(vertShader));
484
485 CheckError(__LINE__);
486 for (i = 0; uniforms[i].name; i++) {
487 uniforms[i].location
488 = glGetUniformLocation_func(program, uniforms[i].name);
489 printf("Uniform %s location: %d\n", uniforms[i].name,
490 uniforms[i].location);
491
492 switch (uniforms[i].size) {
493 case 1:
494 if (uniforms[i].type == GL_INT)
495 glUniform1i_func(uniforms[i].location,
496 (GLint) uniforms[i].value[0]);
497 else
498 glUniform1fv_func(uniforms[i].location, 1, uniforms[i].value);
499 break;
500 case 2:
501 glUniform2fv_func(uniforms[i].location, 1, uniforms[i].value);
502 break;
503 case 3:
504 glUniform3fv_func(uniforms[i].location, 1, uniforms[i].value);
505 break;
506 case 4:
507 glUniform4fv_func(uniforms[i].location, 1, uniforms[i].value);
508 break;
509 default:
510 abort();
511 }
512 }
513
514 CheckError(__LINE__);
515
516 return program;
517 }
518
519
520 static void
521 InitPrograms(void)
522 {
523 Program1 = CreateProgram(ReflectVertFile, CubeFragFile, ReflectUniforms);
524 Program2 = CreateProgram(SimpleVertFile, SimpleTexFragFile, SimpleUniforms);
525 }
526
527
528 static void
529 Init(GLboolean useImageFiles)
530 {
531 const char *version = (const char *) glGetString(GL_VERSION);
532
533 if (version[0] != '2' || version[1] != '.') {
534 printf("Warning: this program expects OpenGL 2.0\n");
535 /*exit(1);*/
536 }
537 printf("GL_RENDERER = %s\n",(const char *) glGetString(GL_RENDERER));
538
539 GetExtensionFuncs();
540
541 InitTextures(useImageFiles);
542 InitPrograms();
543
544 glEnable(GL_DEPTH_TEST);
545
546 glClearColor(.6, .6, .9, 0);
547 glColor3f(1.0, 1.0, 1.0);
548 }
549
550
551 int
552 main(int argc, char *argv[])
553 {
554 glutInit(&argc, argv);
555 glutInitWindowSize(500, 400);
556 glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
557 glutCreateWindow(Demo);
558 glutReshapeFunc(Reshape);
559 glutKeyboardFunc(key);
560 glutSpecialFunc(specialkey);
561 glutDisplayFunc(draw);
562 if (Anim)
563 glutIdleFunc(idle);
564 if (argc > 1 && strcmp(argv[1] , "-i") == 0)
565 Init(1);
566 else
567 Init(0);
568 glutMainLoop();
569 return 0;
570 }