File: shaders.c

package info (click to toggle)
gtkgl2 2.1.0-1
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 448 kB
  • sloc: ansic: 3,004; makefile: 67; sh: 5
file content (482 lines) | stat: -rw-r--r-- 17,073 bytes parent folder | download | duplicates (2)
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
/******************************************************************************
 * Copyright (C) 1999 Chris Abernethy <chris65536@home.com>                   *
 *           (c) 2007 Éric Beets (Uniways-Innovatys) <ericbeets@free.fr>      *
 *                                                                            *
 * This program is free software; you can redistribute it and/or              *
 * modify it under the terms of the GNU General Public License                *
 * as published by the Free Software Foundation; either version 2             *
 * of the License, or (at your option) any later version.                     *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU General Public License for more details.                               *
 *                                                                            *
 * You should have received a copy of the GNU General Public License          *
 * along with this program; if not, write to the Free Software                *
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,     *
 * USA.                                                                       *
 *                                                                            *
 ******************************************************************************
 *
 * This program creates a window with a GtkGLArea widget using a Vertex
 * Shader and a Fragment shader. It should display a coloured texture. A
 * grayscale result means the shaders are not supported.
 *
 ************/

#ifndef GL_GLEXT_PROTOTYPES
#    define GL_GLEXT_PROTOTYPES 1
#endif

#include <GL/gl.h>
#include <gtk/gtk.h>
#include <gtkgl/gtkglarea.h>

#include <stdlib.h>
#include <string.h>


void       create_shader         (void);
void       create_texture_2D     (void);
GtkWidget* create_glarea         (void);
gint       glarea_draw           (GtkWidget*, GdkEventExpose*);
gint       glarea_draw_scene     (void);
gint       glarea_reshape        (GtkWidget*, GdkEventConfigure*);
gint       glarea_init           (GtkWidget*);
gint       glarea_destroy        (GtkWidget*);
int        main                  (int, char**);

#define texture_width   64
#define texture_height  64
static GLubyte texture[texture_height][texture_width][3];

/* Vertex Shader                                */
/*   compute the color from the vertex position */

static char const *vertex_shader_str =
  "varying vec4 color;\n"
  "void main()\n"
  "{\n"
  "  gl_TexCoord[0] = gl_MultiTexCoord0;\n"
  "  float r = float(gl_Vertex.x + 100.0) / 100.0;\n"
  "  float g = float(gl_Vertex.y + 100.0) / 100.0;\n"
  "  color = vec4(1.0 - r, 1.0 - g, 0.0, 1.0);\n"
  "  gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;\n"
  "}\n";

/* Fragment Shader                              */
/*   coordinates texture repeat on X and Y      */
/*   invert coordinates texture (on repetition) */

static char const *fragment_shader_str =
  "varying vec4 color;\n"
  "uniform sampler2D tex;\n"
  "void main()\n"
  "{\n"
  "  vec2 coord, fact;\n"
  "  fact = vec2(1.0, 1.0);\n"
  "  if(gl_TexCoord[0].x > 0.5)\n"
  "    fact.x = -1.0;\n"
  "  if(gl_TexCoord[0].y > 0.5)\n"
  "    fact.y = -1.0;\n"
  "  coord.x = fact.x * gl_TexCoord[0].x * 2.0;\n"
  "  coord.y = fact.y * gl_TexCoord[0].y * 2.0;\n"
  "  gl_FragColor = texture2D(tex, coord) + color;\n"
  "}\n";

/**************************************************/
/*                                                */
/* Function: create_texture_2D (void)             */
/*                                                */
/* This function creates a procedural 2d texture. */
/*                                                */
/**************************************************/

void create_texture_2D (void) {

  int x, y;

  g_print("Creating 2D texture\n");

  for(y = 0; y < texture_height; y++) {
    for(x = 0; x < texture_width; x++) {
      texture[y][x][0] = (x * y) % 255;
      texture[y][x][1] = (x * y) % 255;
      texture[y][x][2] = (x * y) % 255;
    }
  }
}

/********************************************************/
/*                                                      */
/* Function : check_extension(void)                     */
/*                                                      */
/* This function checks for a given GL extension        */
/*                                                      */
/********************************************************/

int check_extension(char const *name)
{
  const char *glExtensions = (const char *)glGetString(GL_EXTENSIONS);
  return (strstr(glExtensions, name) != NULL);
}

/*******************************************************/
/*                                                     */
/* Function: shader_status(int)                        */
/*                                                     */
/* This function checks the shader status and show     */
/* the compilation log                                 */
/*                                                     */
/*******************************************************/

void shader_status(int shader_id)
{
   /* Compilation Test */

   int status;
   glGetShaderiv(shader_id, GL_COMPILE_STATUS, &status);

   /* Display log compilation */

   if (!status)
   {
     int infologLength, charsWritten;
     GLchar *infoLog;
     glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &infologLength);
     infoLog = malloc(sizeof(GLchar) * infologLength);
     glGetShaderInfoLog(shader_id, infologLength, &charsWritten, infoLog);
     g_print("%s", infoLog);
     free(infoLog);
   }
}

/*******************************************************/
/*                                                     */
/* Function: create_shader(void)                       */
/*                                                     */
/* This function creates a Vertex and Fragment Shader, */
/* compile the Program Shader and use it.              */
/*                                                     */
/*******************************************************/

void create_shader (void) {

  int vertex_shader, fragment_shader, prog;

  g_print("Creating shaders\n");

  /* Create Shaders (vertex and fragment) */

  vertex_shader = glCreateShader(GL_VERTEX_SHADER);
  fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);

  /* Source Shader */

  glShaderSource(vertex_shader, 1, &vertex_shader_str, NULL);
  glShaderSource(fragment_shader, 1, &fragment_shader_str, NULL);

  /* Shader source compilation */

  glCompileShader(vertex_shader);
  glCompileShader(fragment_shader);

  /* Create Program */

  prog = glCreateProgram();

  /* Add the shader to the program */

  glAttachShader(prog, vertex_shader);
  glAttachShader(prog, fragment_shader);

  /* Link the shader */

  glLinkProgram(prog);

  /* Check the program */

  glValidateProgram(prog);

  /* Check shaders */

  shader_status(vertex_shader);
  shader_status(fragment_shader);

  /* Activate shaders */
  glUseProgram(prog);
}

/*****************************************************************************/
/*                                                                           */
/* Function: create_glarea (void)                                            */
/*                                                                           */
/* This function performs the necessary operations to construct a GtkGlarea  */
/* widget. These operations include creating the widget, setting the size    */
/* of the widget, and registering callbacks for the widget.                  */
/*                                                                           */
/* This is a good place to add function calls for any GtkGlarea              */
/* initialization that you need to do.                                       */
/*                                                                           */
/*****************************************************************************/

GtkWidget* create_glarea (void) {

  GtkWidget* glarea;

  int attrlist[] = {
    GDK_GL_RGBA,
    GDK_GL_DOUBLEBUFFER,
    GDK_GL_DEPTH_SIZE, 1,
    GDK_GL_NONE
  };

  if(gdk_gl_query() == FALSE) {
    g_print("OpenGL not supported!\n");
    return NULL;
  }

  if ((glarea = gtk_gl_area_new(attrlist)) == NULL) {
    g_print("Error creating GtkGLArea!\n");
    return NULL;
  }

  gtk_widget_set_events(GTK_WIDGET(glarea), GDK_EXPOSURE_MASK);

  g_signal_connect (G_OBJECT(glarea), "expose-event",
                    G_CALLBACK(glarea_draw), NULL);

  g_signal_connect (G_OBJECT(glarea), "configure-event",
                    G_CALLBACK(glarea_reshape), NULL);

  g_signal_connect (G_OBJECT(glarea), "realize",
                    G_CALLBACK(glarea_init), NULL);

  g_signal_connect (G_OBJECT(glarea), "destroy",
                    G_CALLBACK(glarea_destroy), NULL);

  gtk_widget_set_size_request(GTK_WIDGET(glarea), 256, 256);

  return (glarea);

}

/*******************************************************/
/*                                                     */
/* Function: glarea_draw_scene(void)                   */
/*                                                     */
/* This function draws a simple textured quad          */
/*                                                     */
/*******************************************************/

gint glarea_draw_scene (void) {

  /* Draw a simple Quad */
  glBegin(GL_QUADS);
    glTexCoord2f(0.0, 0.0); glVertex3f(-100,-100,0);
    glTexCoord2f(0.0, 1.0); glVertex3f(-100, 100,0);
    glTexCoord2f(1.0, 1.0); glVertex3f( 100, 100,0);
    glTexCoord2f(1.0, 0.0); glVertex3f( 100,-100,0);
  glEnd();

  return(TRUE);
}

/*****************************************************************************/
/*                                                                           */
/* Function: glarea_draw (GtkWidget*, GdkEventExpose*)                       */
/*                                                                           */
/* This is the function that should render your scene to the GtkGLArea. It   */
/* can be used as a callback to the 'Expose' event.                          */
/*                                                                           */
/*****************************************************************************/

gint glarea_draw (GtkWidget* widget, GdkEventExpose* event) {

  if (event->count > 0) {
    return(TRUE);
  }

  if (gtk_gl_area_make_current(GTK_GL_AREA(widget))) {

    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glarea_draw_scene();
    gtk_gl_area_swap_buffers (GTK_GL_AREA(widget));

  }

  return (TRUE);

}

/*****************************************************************************/
/*                                                                           */
/* Function: glarea_reshape (GtkWidget*, GdkEventConfigure*)                 */
/*                                                                           */
/* This function performs the operations needed to maintain the viewing area */
/* of the GtkGLArea. This should be called whenever the size of the area     */
/* is changed.                                                               */
/*                                                                           */
/*****************************************************************************/

gint glarea_reshape (GtkWidget* widget, GdkEventConfigure* event) {

  GtkAllocation allocation;
  gtk_widget_get_allocation (widget, &allocation);
  int w = allocation.width;
  int h = allocation.height;

  if (gtk_gl_area_make_current (GTK_GL_AREA(widget))) {

    glViewport (0, 0, w, h);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    glOrtho (-(w>>1), (w>>1), -(h>>1), h>>1, -1, 1);
    glMatrixMode (GL_MODELVIEW);

  }

  return (TRUE);

}

/*****************************************************************************/
/*                                                                           */
/* Function: glarea_init (GtkWidget*)                                        */
/*                                                                           */
/* This function is a callback for the realization of the GtkGLArea widtget. */
/* You should do any OpenGL initialization here.                             */
/*                                                                           */
/*****************************************************************************/

gint glarea_init (GtkWidget* widget) {

  if (gtk_gl_area_make_current (GTK_GL_AREA(widget))) {

    /* Procedural texture creation */

    create_texture_2D ();

    /* Check, Create and Activate shaders */

    if(!check_extension("GL_ARB_fragment_shader"))
      fprintf(stderr, "Warning: GL_ARB_fragment_shader extension not present\n");
    else if(!check_extension("GL_ARB_vertex_shader"))
      fprintf(stderr, "Warning: GL_ARB_vertex_shader extension not present\n");
    else
      create_shader();

    /* Activate and parameterization texture context */

    glEnable(GL_TEXTURE_2D);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texture_width, texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  }

  return TRUE;

}

/*****************************************************************************/
/*                                                                           */
/* Function: glarea_destroy (GtkWidget*)                                     */
/*                                                                           */
/* This function is a callback for the main GtkGLArea. It deletes should     */
/* delete any data structures stored in the GtkGLArea.                       */
/*                                                                           */
/*****************************************************************************/

gint glarea_destroy (GtkWidget* widget) {

  g_print ("GTK GL Area destroy event\n");

  /* Insert any required cleanup */
  /* code here.                  */

  return TRUE;

}

/*****************************************************************************/
/*                                                                           */
/* Function: main (int, char**)                                              */
/*                                                                           */
/* The main function sets up our GUI and calls the functions needed to       */
/* create our GtkGLArea.                                                     */
/*                                                                           */
/*****************************************************************************/

int main (int argc, char** argv) {

  GtkWidget* window;
  GtkWidget* button_quit;
  GtkWidget* message;
  GtkWidget* box_main;
  GtkWidget* glarea;

  gtk_init (&argc, &argv);

  /* Main widget container */

  box_main = gtk_vbox_new (FALSE, 10);

  /* GTK GL Area */

  glarea = create_glarea ();

  /* Information message */

  message = gtk_label_new ("If the above drawing consists only of\n"
                           "shades of grey, your hardware or your\n"
                           "drivers do not support fragment shaders.");

  /* Quit button */

  button_quit = gtk_button_new_with_label ("Quit");

  g_signal_connect (G_OBJECT(button_quit), "clicked",
                    G_CALLBACK(gtk_main_quit), NULL);

  /* Main window */

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  gtk_window_set_title (GTK_WINDOW(window), "GtkGLArea Shader Demo");

  /* destroy this window when exiting from gtk_main() */

  gtk_quit_add_destroy (1, GTK_OBJECT(window));

  g_signal_connect (G_OBJECT(window), "delete-event",
                    G_CALLBACK(gtk_main_quit), NULL);

  g_signal_connect (G_OBJECT (window), "destroy",
                    G_CALLBACK(gtk_main_quit), NULL);

  gtk_container_set_border_width (GTK_CONTAINER(window), 10);

  /* Pack everything into the main box, add the main box to */
  /* the top-level window, and 'show' all of the widgets.   */
  /* The window is 'shown' last so that when the user sees  */
  /* it, it's contents are already there. Otherwise they    */
  /* might see each widget come up.                         */

  gtk_box_pack_start (GTK_BOX(box_main), glarea,      TRUE,  TRUE, 0);
  gtk_box_pack_start (GTK_BOX(box_main), message,     FALSE, TRUE, 0);
  gtk_box_pack_start (GTK_BOX(box_main), button_quit, FALSE, TRUE, 0);
  gtk_container_add (GTK_CONTAINER(window), box_main);

  gtk_widget_show (glarea);
  gtk_widget_show (message);
  gtk_widget_show (button_quit);
  gtk_widget_show (box_main);
  gtk_widget_show (window);

  gtk_main ();

  return (0);

}