SimpleGL example: Difference between revisions

From Maemo Wiki
Jump to navigationJump to search
imported>mr_smiley
New page: #include <stdio.h> #include <stdlib.h> #include <X11/Xatom.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <GLES2/gl2.h> #include <EGL/egl.h> #include <math.h> #include <...
 
Change only_if_exists to False, then the atom is created if it does not exist to avoid return invalid atom.
 
(13 intermediate revisions by 6 users not shown)
Line 1: Line 1:
#include <stdio.h>
This is a simple program demonstrating how to use [[OpenGL-ES#OpenGL_variants|OpenGL ES 2.0]]. It will output this animated spiral, which can be moved around on the screen:
#include <stdlib.h>
 
#include <X11/Xatom.h>
[[Image:Egl-example_output.png]]
#include <X11/Xlib.h>
 
  #include <X11/Xutil.h>
<source lang="cpp">
  #include <GLES2/gl2.h>
/* Created by exoticorn ( http://talk.maemo.org/showthread.php?t=37356 )
  #include <EGL/egl.h>
  * edited and commented by André Bergner [endboss]
  #include <math.h>
  *
#include <sys/time.h>
  * libraries needed:  libx11-dev, libgles2-dev
#include <unistd.h>
*
  #include <string.h>
* compile with:  g++  -lX11 -lEGL -lGLESv2  egl-example.cpp
   
  */
  const char* vertexSrc = "attribute vec4 position; varying mediump vec2 pos; uniform vec4 offset; void main() { gl_Position = position + offset; pos = position.xy; }";
 
  const char* fragmentSrc = "varying mediump vec2 pos; uniform mediump float phase; void main() { gl_FragColor = vec4(1, 1, 1, 1) * sin((pos.x * pos.x + pos.y * pos.y) * 40.0 + phase); }";
#include <iostream>
#include <cstdlib>
void printShaderInfoLog(GLuint shader) {
#include <cstring>
        GLint length;
using namespace std;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
 
        if(length) {
#include <cmath>
                char* buffer = new char[length];
#include <sys/time.h>
                glGetShaderInfoLog(shader, length, NULL, buffer);
 
                printf("%s", buffer);
#include <X11/Xlib.h>
                delete [] buffer;
#include <X11/Xatom.h>
                GLint success;
#include  <X11/Xutil.h>
                glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
 
                if(success != GL_TRUE) {
#include <GLES2/gl2.h>
                        exit(1);
#include  <EGL/egl.h>
                }
 
        }
 
  }
 
const char vertex_src [] =
GLuint createShader(GLenum type, const char* pSource) {
"                                       \
        GLuint shader = glCreateShader(type);
  attribute vec4        position;      \
        glShaderSource(shader, 1, &pSource, NULL);
  varying mediump vec2 pos;           \
        glCompileShader(shader);
  uniform vec4          offset;         \
        printShaderInfoLog(shader);
                                        \
        return shader;
  void main()                           \
}
  {                                     \
      gl_Position = position + offset;  \
Display* dpy;
      pos = position.xy;                \
Window win;
  }                                    \
EGLDisplay edpy;
";
EGLContext ectxt;
 
int phaseLocation;
 
GLfloat norm_x;
const char fragment_src [] =
GLfloat norm_y;
"                                                      \
GLfloat offset_x = 0.0;
  varying mediump vec2    pos;                       \
GLfloat offset_y = 0.0;
  uniform mediump float  phase;                     \
GLfloat p1_pos_x;
                                                      \
GLfloat p1_pos_y;
  void  main()                                       \
  {                                                   \
GLint offset;
      gl_FragColor  = vec4( 1., 0.9, 0.7, 1.0 ) *    \
EGLSurface esfc;
        cos( 30.*sqrt(pos.x*pos.x + 1.5*pos.y*pos.y)   \
bool update_pos = false;
            + atan(pos.y,pos.x) - phase );           \
  }                                                   \
  const float vertexArray[] = {
";
        -0.85, -1, 0, 1,
// some more formulas to play with...
        -1, -0.7, 0, 1,
//      cos( 20.*(pos.x*pos.x + pos.y*pos.y) - phase );
        -0.7, -0.7, 0, 1
//      cos( 20.*sqrt(pos.x*pos.x + pos.y*pos.y) + atan(pos.y,pos.x) - phase );
  };
//      cos( 30.*sqrt(pos.x*pos.x + 1.5*pos.y*pos.y - 1.8*pos.x*pos.y*pos.y)
//            + atan(pos.y,pos.x) - phase );
void render() {
 
                static float offset_blah = 0;
 
                static int donesetup=0;
void
                static XWindowAttributes gwa;
print_shader_info_log (
  GLuint shader      // handle to the shader
                // draw
)
{
                if (!donesetup) {
  GLint  length;
                        XWindowAttributes gwa;
 
                        XGetWindowAttributes(dpy, win, &gwa);
  glGetShaderiv ( shader , GL_INFO_LOG_LENGTH , &length );
                        glViewport(0, 0, gwa.width, gwa.height);
 
                        glClearColor(0, 1, 0, 1);
  if ( length ) {
                        donesetup = 1;
      char* buffer  = new char [ length ];
                }
      glGetShaderInfoLog ( shader , length , NULL , buffer );
                glClear(GL_COLOR_BUFFER_BIT);
      cout << "shader info: " <<  buffer << flush;
   
      delete [] buffer;
                glUniform1f(phaseLocation, offset_blah);
 
      GLint success;
                if (update_pos) {
      glGetShaderiv( shader, GL_COMPILE_STATUS, &success );
                        GLfloat old_offset_x = offset_x;
      if ( success != GL_TRUE )   exit ( 1 );
                        GLfloat old_offset_y = offset_y;
  }
   
}
                offset_x = norm_x - p1_pos_x;
 
                offset_y = norm_y - p1_pos_y;
 
GLuint
                        p1_pos_x = norm_x;
load_shader (
                        p1_pos_y = norm_y;
  const char *shader_source,
  GLenum      type
                        offset_x += old_offset_x;
)
                        offset_y += old_offset_y;
{
   
  GLuint  shader = glCreateShader( type );
                        update_pos = false;
 
                }
  glShaderSource ( shader , 1 , &shader_source , NULL );
   
  glCompileShader ( shader );
                glUniform4f(offset, offset_x, offset_y, 0, 0);
 
  print_shader_info_log ( shader );
                glVertexAttribPointer(0, 4, GL_FLOAT, false, 0, vertexArray);
 
                glEnableVertexAttribArray(0);
  return shader;
                glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
}
 
                eglSwapBuffers(edpy, esfc);
 
Display    *x_display;
                offset_blah = fmodf(offset_blah + 0.5, 2*3.141f);
Window      win;
  }
EGLDisplay  egl_display;
   
EGLContext egl_context;
  int main() {
EGLSurface  egl_surface;
        dpy = XOpenDisplay(NULL);
 
        if(dpy == NULL) {
GLfloat
                printf("cannot connect to X server\n");
  norm_x    = 0.0,
                return 1;
  norm_y    =  0.0,
        }
  offset_x =  0.0,
  offset_y =  0.0,
        Window root = DefaultRootWindow(dpy);
  p1_pos_x  =  0.0,
   
  p1_pos_y  =  0.0;
        XSetWindowAttributes swa;
 
        swa.event_mask = ExposureMask | PointerMotionMask;
GLint
  phase_loc,
        win = XCreateWindow(dpy, root, 0, 0, 600, 400, 0, CopyFromParent, InputOutput, CopyFromParent, CWEventMask, &swa);
  offset_loc,
  position_loc;
        XSetWindowAttributes xattr;
 
        Atom atom;
 
        int one = 1;
bool        update_pos = false;
 
        xattr.override_redirect = False;
const float vertexArray[] = {
        XChangeWindowAttributes(dpy, win, CWOverrideRedirect, &xattr);
  0.0,  0.5, 0.0,
   
  -0.5, 0.0, 0.0,
        atom = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", True);
  0.0, -0.5, 0.0,
        XChangeProperty(dpy, win, XInternAtom(dpy, "_NET_WM_STATE", True),
  0.5,  0.0,  0.0,
                XA_ATOM, 32, PropModeReplace,
  0.0,  0.5,  0.0
                (unsigned char *) &atom, 1);
};
   
 
        XChangeProperty(dpy, win, XInternAtom(dpy, "_HILDON_NON_COMPOSITED_WINDOW", True),
 
                XA_INTEGER, 32, PropModeReplace,
void  render()
                (unsigned char *) &one, 1);
{
   
  static float  phase = 0;
        XMapWindow(dpy, win);
  static int    donesetup = 0;
   
 
        XStoreName(dpy, win, "GL test");
  static XWindowAttributes gwa;
   
 
        Atom wm_state = XInternAtom(dpy, "_NET_WM_STATE", False);
  //// draw
        Atom fullscreen = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
 
  if ( !donesetup ) {
        XEvent xev;
      XWindowAttributes gwa;
        memset(&xev, 0, sizeof(xev));
      XGetWindowAttributes ( x_display , win , &gwa );
        xev.type = ClientMessage;
      glViewport ( 0 , 0 , gwa.width , gwa.height );
        xev.xclient.window = win;
      glClearColor ( 0.08 , 0.06 , 0.07 , 1.);   // background color
        xev.xclient.message_type = wm_state;
      donesetup = 1;
        xev.xclient.format = 32;
  }
        xev.xclient.data.l[0] = 1;
  glClear ( GL_COLOR_BUFFER_BIT );
        xev.xclient.data.l[1] = fullscreen;
 
        XSendEvent(dpy, DefaultRootWindow(dpy), False, SubstructureNotifyMask, &xev);
  glUniform1f ( phase_loc , phase );  // write the value of phase to the shaders phase
  phase  = fmodf ( phase + 0.5f , 2.f * 3.141f );   // and update the local variable
        edpy = eglGetDisplay((EGLNativeDisplayType)dpy);
 
        if(edpy == EGL_NO_DISPLAY) {
  if ( update_pos ) {  // if the position of the texture has changed due to user action
                printf("Got no EGL display\n");
      GLfloat old_offset_x  =  offset_x;
                return 1;
      GLfloat old_offset_y  =  offset_y;
        }
 
      offset_x =  norm_x - p1_pos_x;
        if(!eglInitialize(edpy, NULL, NULL)) {
      offset_y  =  norm_y - p1_pos_y;
                printf("Unable to initialize EGL\n");
 
                return 1;
      p1_pos_x  =  norm_x;
        }
      p1_pos_y  = norm_y;
   
 
        EGLint attr[] = {
      offset_x +=  old_offset_x;
                EGL_BUFFER_SIZE, 16,
      offset_y += old_offset_y;
                EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
 
                EGL_NONE
      update_pos = false;
        };
  }
   
 
        EGLConfig ecfg;
  glUniform4f ( offset_loc  ,  offset_x , offset_y , 0.0 , 0.0 );
        EGLint num_config;
 
        if(!eglChooseConfig(edpy, attr, &ecfg, 1, &num_config)) {
  glVertexAttribPointer ( position_loc, 3, GL_FLOAT, false, 0, vertexArray );
                printf("Failed to choose config (%x)\n", eglGetError());
  glEnableVertexAttribArray ( position_loc );
                return 1;
  glDrawArrays ( GL_TRIANGLE_STRIP, 0, 5 );
        }
 
        if(num_config != 1) {
  eglSwapBuffers ( egl_display, egl_surface ); // get the rendered buffer to the screen
                printf("Didn't get exactly one config, but %d\n", num_config);
}
                return 1;
 
        }
 
   
////////////////////////////////////////////////////////////////////////////////////////////
        esfc = eglCreateWindowSurface(edpy, ecfg, (void*)win, NULL);
 
        if(esfc == EGL_NO_SURFACE) {
 
                printf("Unable to create EGL surface (%x)\n", eglGetError());
int  main()
                return 1;
{
        }
  /////// the X11 part //////////////////////////////////////////////////////////////////
   
  // in the first part the program opens a connection to the X11 window manager
        EGLint ctxattr[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
  //
        ectxt = eglCreateContext(edpy, ecfg, EGL_NO_CONTEXT, ctxattr);
 
        if(ectxt == EGL_NO_CONTEXT) {
  x_display = XOpenDisplay ( NULL );  // open the standard display (the primary screen)
                printf("Unable to create EGL context (%x)\n", eglGetError());
  if ( x_display == NULL ) {
                return 1;
      cerr << "cannot connect to X server" << endl;
      return 1;
  }
 
  Window root = DefaultRootWindow( x_display );  // get the root window (usually the whole screen)
 
  XSetWindowAttributes  swa;
  swa.event_mask  = ExposureMask | PointerMotionMask | KeyPressMask;
 
  win  = XCreateWindow (   // create a window with the provided parameters
              x_display, root,
              0, 0, 800, 480,  0,
              CopyFromParent, InputOutput,
              CopyFromParent, CWEventMask,
              &swa );
 
  XSetWindowAttributes xattr;
  Atom  atom;
  int  one = 1;
 
  xattr.override_redirect = False;
  XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr );
 
  atom = XInternAtom ( x_display, "_NET_WM_STATE_FULLSCREEN", True );
  XChangeProperty (
      x_display, win,
      XInternAtom ( x_display, "_NET_WM_STATE", True ),
      XA_ATOM,  32,  PropModeReplace,
      (unsigned char*) &atom,  1 );
 
  XChangeProperty (
      x_display, win,
      XInternAtom ( x_display, "_HILDON_NON_COMPOSITED_WINDOW", False ),
      XA_INTEGER,  32,  PropModeReplace,
      (unsigned char*) &one,  1);
 
  XWMHints hints;
  hints.input = True;
  hints.flags = InputHint;
  XSetWMHints(x_display, win, &hints);
 
  XMapWindow ( x_display , win );            // make the window visible on the screen
  XStoreName ( x_display , win , "GL test" ); // give the window a name
 
  //// get identifiers for the provided atom name strings
  Atom wm_state  = XInternAtom ( x_display, "_NET_WM_STATE", False );
  Atom fullscreen = XInternAtom ( x_display, "_NET_WM_STATE_FULLSCREEN", False );
 
  XEvent xev;
  memset ( &xev, 0, sizeof(xev) );
 
  xev.type                = ClientMessage;
  xev.xclient.window      = win;
  xev.xclient.message_type = wm_state;
  xev.xclient.format      = 32;
  xev.xclient.data.l[0]    = 1;
  xev.xclient.data.l[1]    = fullscreen;
  XSendEvent (                // send an event mask to the X-server
      x_display,
      DefaultRootWindow ( x_display ),
      False,
      SubstructureNotifyMask,
      &xev );
 
 
  ///////  the egl part  //////////////////////////////////////////////////////////////////
  //  egl provides an interface to connect the graphics related functionality of openGL ES
  //  with the windowing interface and functionality of the native operation system (X11
  //  in our case.
 
  egl_display  =  eglGetDisplay( (EGLNativeDisplayType) x_display );
  if ( egl_display == EGL_NO_DISPLAY ) {
      cerr << "Got no EGL display." << endl;
      return 1;
  }
 
  if ( !eglInitialize( egl_display, NULL, NULL ) ) {
      cerr << "Unable to initialize EGL" << endl;
      return 1;
  }
 
  EGLint attr[] = {      // some attributes to set up our egl-interface
      EGL_BUFFER_SIZE, 16,
      EGL_RENDERABLE_TYPE,
      EGL_OPENGL_ES2_BIT,
      EGL_NONE
  };
 
  EGLConfig  ecfg;
  EGLint    num_config;
  if ( !eglChooseConfig( egl_display, attr, &ecfg, 1, &num_config ) ) {
      cerr << "Failed to choose config (eglError: " << eglGetError() << ")" << endl;
      return 1;
  }
 
  if ( num_config != 1 ) {
      cerr << "Didn't get exactly one config, but " << num_config << endl;
      return 1;
  }
 
  egl_surface = eglCreateWindowSurface ( egl_display, ecfg, win, NULL );
  if ( egl_surface == EGL_NO_SURFACE ) {
      cerr << "Unable to create EGL surface (eglError: " << eglGetError() << ")" << endl;
      return 1;
  }
 
  //// egl-contexts collect all state descriptions needed required for operation
  EGLint ctxattr[] = {
      EGL_CONTEXT_CLIENT_VERSION, 2,
      EGL_NONE
  };
  egl_context = eglCreateContext ( egl_display, ecfg, EGL_NO_CONTEXT, ctxattr );
  if ( egl_context == EGL_NO_CONTEXT ) {
      cerr << "Unable to create EGL context (eglError: " << eglGetError() << ")" << endl;
      return 1;
  }
 
  //// associate the egl-context with the egl-surface
  eglMakeCurrent( egl_display, egl_surface, egl_surface, egl_context );
 
 
  ///////  the openGL part  ///////////////////////////////////////////////////////////////
 
  GLuint vertexShader  = load_shader ( vertex_src , GL_VERTEX_SHADER  );    // load vertex shader
  GLuint fragmentShader = load_shader ( fragment_src , GL_FRAGMENT_SHADER );  // load fragment shader
 
  GLuint shaderProgram  = glCreateProgram ();                // create program object
  glAttachShader ( shaderProgram, vertexShader );            // and attach both...
  glAttachShader ( shaderProgram, fragmentShader );          // ... shaders to it
 
  glLinkProgram ( shaderProgram );    // link the program
  glUseProgram  ( shaderProgram );    // and select it for usage
 
  //// now get the locations (kind of handle) of the shaders variables
  position_loc  = glGetAttribLocation  ( shaderProgram , "position" );
  phase_loc    = glGetUniformLocation ( shaderProgram , "phase"    );
  offset_loc    = glGetUniformLocation ( shaderProgram , "offset"  );
  if ( position_loc < 0  ||  phase_loc < 0  ||  offset_loc < 0 ) {
      cerr << "Unable to get uniform location" << endl;
      return 1;
  }
 
 
  const float
      window_width  = 800.0,
      window_height = 480.0;
 
  //// this is needed for time measuring  -->  frames per second
  struct  timezone  tz;
  timeval  t1, t2;
  gettimeofday ( &t1 , &tz );
  int  num_frames = 0;
 
  bool quit = false;
  while ( !quit ) {    // the main loop
 
      while ( XPending ( x_display ) ) {  // check for events from the x-server
 
        XEvent  xev;
        XNextEvent( x_display, &xev );
 
        if ( xev.type == MotionNotify ) {  // if mouse has moved
//            cout << "move to: << xev.xmotion.x << "," << xev.xmotion.y << endl;
            GLfloat window_y  =  (window_height - xev.xmotion.y) - window_height / 2.0;
            norm_y            =  window_y / (window_height / 2.0);
            GLfloat window_x  =  xev.xmotion.x - window_width / 2.0;
            norm_x            =  window_x / (window_width / 2.0);
            update_pos = true;
         }
         }
        eglMakeCurrent(edpy, esfc, esfc, ectxt);
 
         if ( xev.type == KeyPress )   quit = true;
        GLuint shaderProgram = glCreateProgram();
      }
        GLuint vertexShader = createShader(GL_VERTEX_SHADER, vertexSrc);
 
        GLuint fragmentShader = createShader(GL_FRAGMENT_SHADER, fragmentSrc);
      render();   // now we finally put something on the screen
 
        glAttachShader(shaderProgram, vertexShader);
      if ( ++num_frames % 100 == 0 ) {
        glAttachShader(shaderProgram, fragmentShader);
        gettimeofday( &t2, &tz );
        float dt  = t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) * 1e-6;
        glLinkProgram(shaderProgram);
        cout << "fps: " << num_frames / dt << endl;
        num_frames = 0;
        glUseProgram(shaderProgram);
        t1 = t2;
      }
        phaseLocation = glGetUniformLocation(shaderProgram, "phase");
//      usleep( 1000*10 );
        offset = glGetUniformLocation(shaderProgram, "offset");
  }
         if(phaseLocation < 0) {
 
                printf("Unable to get uniform location\n");
 
                return 1;
  //// cleaning up...
        }
  eglDestroyContext ( egl_display, egl_context );
  eglDestroySurface ( egl_display, egl_surface );
        bool quit = false;
  eglTerminate     ( egl_display );
  XDestroyWindow   ( x_display, win );
        timeval startTime;
  XCloseDisplay     ( x_display );
        timezone tz;
 
        gettimeofday(&startTime, &tz);
  return 0;
        int numFrames = 0;
}
</source>
        float window_width = 800.0;
        float window_height = 480.0;
        norm_x = -0.85;
        norm_y = -1;
        p1_pos_x = -0.85;
        p1_pos_y = -1;
        while(!quit) {
                while(XPending(dpy)) {
                        XEvent xev;
                        XNextEvent(dpy, &xev);
                        if(xev.type == MotionNotify) {
                                //printf("move to: (%d,%d)\n", xev.xmotion.x, xev.xmotion.y);
                            GLfloat window_y = (window_height - xev.xmotion.y) - window_height / 2.0;
                            norm_y = window_y / (window_height / 2.0);
                            GLfloat window_x = xev.xmotion.x - window_width / 2.0;
                            norm_x = window_x / (window_width / 2.0);
                                update_pos = true;
                                //quit = true;
                        }
                }
                                render();
                                numFrames++;
                                if(numFrames % 100 == 0) {
                                        timeval now;
                                        gettimeofday(&now, &tz);
                                        float delta = now.tv_sec - startTime.tv_sec + (now.tv_usec - startTime.tv_usec) * 0.000001f;
                                        printf("fps: %f\n", numFrames / delta);
                                }
                                usleep(1000*30);
        }
   
        eglDestroyContext(edpy, ectxt);
        eglDestroySurface(edpy, esfc);
        eglTerminate(edpy);
        XDestroyWindow(dpy, win);
        XCloseDisplay(dpy);
   
   
        return 0;
[[Category:Development]]
}
[[Category:Fremantle]]

Latest revision as of 02:51, 26 July 2017

This is a simple program demonstrating how to use OpenGL ES 2.0. It will output this animated spiral, which can be moved around on the screen:

<source lang="cpp"> /* Created by exoticorn ( http://talk.maemo.org/showthread.php?t=37356 )

* edited and commented by André Bergner [endboss]
*
* libraries needed:   libx11-dev, libgles2-dev
*
* compile with:   g++  -lX11 -lEGL -lGLESv2  egl-example.cpp
*/
  1. include <iostream>
  2. include <cstdlib>
  3. include <cstring>

using namespace std;

  1. include <cmath>
  2. include <sys/time.h>
  1. include <X11/Xlib.h>
  2. include <X11/Xatom.h>
  3. include <X11/Xutil.h>
  1. include <GLES2/gl2.h>
  2. include <EGL/egl.h>


const char vertex_src [] = " \

  attribute vec4        position;       \
  varying mediump vec2  pos;            \
  uniform vec4          offset;         \
                                        \
  void main()                           \
  {                                     \
     gl_Position = position + offset;   \
     pos = position.xy;                 \
  }                                     \

";


const char fragment_src [] = " \

  varying mediump vec2    pos;                        \
  uniform mediump float   phase;                      \
                                                      \
  void  main()                                        \
  {                                                   \
     gl_FragColor  =  vec4( 1., 0.9, 0.7, 1.0 ) *     \
       cos( 30.*sqrt(pos.x*pos.x + 1.5*pos.y*pos.y)   \
            + atan(pos.y,pos.x) - phase );            \
  }                                                   \

"; // some more formulas to play with... // cos( 20.*(pos.x*pos.x + pos.y*pos.y) - phase ); // cos( 20.*sqrt(pos.x*pos.x + pos.y*pos.y) + atan(pos.y,pos.x) - phase ); // cos( 30.*sqrt(pos.x*pos.x + 1.5*pos.y*pos.y - 1.8*pos.x*pos.y*pos.y) // + atan(pos.y,pos.x) - phase );


void print_shader_info_log (

  GLuint  shader      // handle to the shader

) {

  GLint  length;
  glGetShaderiv ( shader , GL_INFO_LOG_LENGTH , &length );
  if ( length ) {
     char* buffer  =  new char [ length ];
     glGetShaderInfoLog ( shader , length , NULL , buffer );
     cout << "shader info: " <<  buffer << flush;
     delete [] buffer;
     GLint success;
     glGetShaderiv( shader, GL_COMPILE_STATUS, &success );
     if ( success != GL_TRUE )   exit ( 1 );
  }

}


GLuint load_shader (

  const char  *shader_source,
  GLenum       type

) {

  GLuint  shader = glCreateShader( type );
  glShaderSource  ( shader , 1 , &shader_source , NULL );
  glCompileShader ( shader );
  print_shader_info_log ( shader );
  return shader;

}


Display *x_display; Window win; EGLDisplay egl_display; EGLContext egl_context; EGLSurface egl_surface;

GLfloat

  norm_x    =  0.0,
  norm_y    =  0.0,
  offset_x  =  0.0,
  offset_y  =  0.0,
  p1_pos_x  =  0.0,
  p1_pos_y  =  0.0;

GLint

  phase_loc,
  offset_loc,
  position_loc;


bool update_pos = false;

const float vertexArray[] = {

  0.0,  0.5,  0.0,
 -0.5,  0.0,  0.0,
  0.0, -0.5,  0.0,
  0.5,  0.0,  0.0,
  0.0,  0.5,  0.0 

};


void render() {

  static float  phase = 0;
  static int    donesetup = 0;
  static XWindowAttributes gwa;
  //// draw
  if ( !donesetup ) {
     XWindowAttributes  gwa;
     XGetWindowAttributes ( x_display , win , &gwa );
     glViewport ( 0 , 0 , gwa.width , gwa.height );
     glClearColor ( 0.08 , 0.06 , 0.07 , 1.);    // background color
     donesetup = 1;
  }
  glClear ( GL_COLOR_BUFFER_BIT );
  glUniform1f ( phase_loc , phase );  // write the value of phase to the shaders phase
  phase  =  fmodf ( phase + 0.5f , 2.f * 3.141f );    // and update the local variable
  if ( update_pos ) {  // if the position of the texture has changed due to user action
     GLfloat old_offset_x  =  offset_x;
     GLfloat old_offset_y  =  offset_y;
     offset_x  =  norm_x - p1_pos_x;
     offset_y  =  norm_y - p1_pos_y;
     p1_pos_x  =  norm_x;
     p1_pos_y  =  norm_y;
     offset_x  +=  old_offset_x;
     offset_y  +=  old_offset_y;
     update_pos = false;
  }
  glUniform4f ( offset_loc  ,  offset_x , offset_y , 0.0 , 0.0 );
  glVertexAttribPointer ( position_loc, 3, GL_FLOAT, false, 0, vertexArray );
  glEnableVertexAttribArray ( position_loc );
  glDrawArrays ( GL_TRIANGLE_STRIP, 0, 5 );
  eglSwapBuffers ( egl_display, egl_surface );  // get the rendered buffer to the screen

}


////////////////////////////////////////////////////////////////////////////////////////////


int main() {

  ///////  the X11 part  //////////////////////////////////////////////////////////////////
  // in the first part the program opens a connection to the X11 window manager
  //
  x_display = XOpenDisplay ( NULL );   // open the standard display (the primary screen)
  if ( x_display == NULL ) {
     cerr << "cannot connect to X server" << endl;
     return 1;
  }
  Window root  =  DefaultRootWindow( x_display );   // get the root window (usually the whole screen)
  XSetWindowAttributes  swa;
  swa.event_mask  =  ExposureMask | PointerMotionMask | KeyPressMask;
  win  =  XCreateWindow (   // create a window with the provided parameters
             x_display, root,
             0, 0, 800, 480,   0,
             CopyFromParent, InputOutput,
             CopyFromParent, CWEventMask,
             &swa );
  XSetWindowAttributes  xattr;
  Atom  atom;
  int   one = 1;
  xattr.override_redirect = False;
  XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr );
  atom = XInternAtom ( x_display, "_NET_WM_STATE_FULLSCREEN", True );
  XChangeProperty (
     x_display, win,
     XInternAtom ( x_display, "_NET_WM_STATE", True ),
     XA_ATOM,  32,  PropModeReplace,
     (unsigned char*) &atom,  1 );
  XChangeProperty (
     x_display, win,
     XInternAtom ( x_display, "_HILDON_NON_COMPOSITED_WINDOW", False ),
     XA_INTEGER,  32,  PropModeReplace,
     (unsigned char*) &one,  1);
  XWMHints hints;
  hints.input = True;
  hints.flags = InputHint;
  XSetWMHints(x_display, win, &hints);
  XMapWindow ( x_display , win );             // make the window visible on the screen
  XStoreName ( x_display , win , "GL test" ); // give the window a name
  //// get identifiers for the provided atom name strings
  Atom wm_state   = XInternAtom ( x_display, "_NET_WM_STATE", False );
  Atom fullscreen = XInternAtom ( x_display, "_NET_WM_STATE_FULLSCREEN", False );
  XEvent xev;
  memset ( &xev, 0, sizeof(xev) );
  xev.type                 = ClientMessage;
  xev.xclient.window       = win;
  xev.xclient.message_type = wm_state;
  xev.xclient.format       = 32;
  xev.xclient.data.l[0]    = 1;
  xev.xclient.data.l[1]    = fullscreen;
  XSendEvent (                // send an event mask to the X-server
     x_display,
     DefaultRootWindow ( x_display ),
     False,
     SubstructureNotifyMask,
     &xev );


  ///////  the egl part  //////////////////////////////////////////////////////////////////
  //  egl provides an interface to connect the graphics related functionality of openGL ES
  //  with the windowing interface and functionality of the native operation system (X11
  //  in our case.
  egl_display  =  eglGetDisplay( (EGLNativeDisplayType) x_display );
  if ( egl_display == EGL_NO_DISPLAY ) {
     cerr << "Got no EGL display." << endl;
     return 1;
  }
  if ( !eglInitialize( egl_display, NULL, NULL ) ) {
     cerr << "Unable to initialize EGL" << endl;
     return 1;
  }
  EGLint attr[] = {       // some attributes to set up our egl-interface
     EGL_BUFFER_SIZE, 16,
     EGL_RENDERABLE_TYPE,
     EGL_OPENGL_ES2_BIT,
     EGL_NONE
  };
  EGLConfig  ecfg;
  EGLint     num_config;
  if ( !eglChooseConfig( egl_display, attr, &ecfg, 1, &num_config ) ) {
     cerr << "Failed to choose config (eglError: " << eglGetError() << ")" << endl;
     return 1;
  }
  if ( num_config != 1 ) {
     cerr << "Didn't get exactly one config, but " << num_config << endl;
     return 1;
  }
  egl_surface = eglCreateWindowSurface ( egl_display, ecfg, win, NULL );
  if ( egl_surface == EGL_NO_SURFACE ) {
     cerr << "Unable to create EGL surface (eglError: " << eglGetError() << ")" << endl;
     return 1;
  }
  //// egl-contexts collect all state descriptions needed required for operation
  EGLint ctxattr[] = {
     EGL_CONTEXT_CLIENT_VERSION, 2,
     EGL_NONE
  };
  egl_context = eglCreateContext ( egl_display, ecfg, EGL_NO_CONTEXT, ctxattr );
  if ( egl_context == EGL_NO_CONTEXT ) {
     cerr << "Unable to create EGL context (eglError: " << eglGetError() << ")" << endl;
     return 1;
  }
  //// associate the egl-context with the egl-surface
  eglMakeCurrent( egl_display, egl_surface, egl_surface, egl_context );


  ///////  the openGL part  ///////////////////////////////////////////////////////////////
  GLuint vertexShader   = load_shader ( vertex_src , GL_VERTEX_SHADER  );     // load vertex shader
  GLuint fragmentShader = load_shader ( fragment_src , GL_FRAGMENT_SHADER );  // load fragment shader
  GLuint shaderProgram  = glCreateProgram ();                 // create program object
  glAttachShader ( shaderProgram, vertexShader );             // and attach both...
  glAttachShader ( shaderProgram, fragmentShader );           // ... shaders to it
  glLinkProgram ( shaderProgram );    // link the program
  glUseProgram  ( shaderProgram );    // and select it for usage
  //// now get the locations (kind of handle) of the shaders variables
  position_loc  = glGetAttribLocation  ( shaderProgram , "position" );
  phase_loc     = glGetUniformLocation ( shaderProgram , "phase"    );
  offset_loc    = glGetUniformLocation ( shaderProgram , "offset"   );
  if ( position_loc < 0  ||  phase_loc < 0  ||  offset_loc < 0 ) {
     cerr << "Unable to get uniform location" << endl;
     return 1;
  }


  const float
     window_width  = 800.0,
     window_height = 480.0;
  //// this is needed for time measuring  -->  frames per second
  struct  timezone  tz;
  timeval  t1, t2;
  gettimeofday ( &t1 , &tz );
  int  num_frames = 0;
  bool quit = false;
  while ( !quit ) {    // the main loop
     while ( XPending ( x_display ) ) {   // check for events from the x-server
        XEvent  xev;
        XNextEvent( x_display, &xev );
        if ( xev.type == MotionNotify ) {  // if mouse has moved

// cout << "move to: << xev.xmotion.x << "," << xev.xmotion.y << endl;

           GLfloat window_y  =  (window_height - xev.xmotion.y) - window_height / 2.0;
           norm_y            =  window_y / (window_height / 2.0);
           GLfloat window_x  =  xev.xmotion.x - window_width / 2.0;
           norm_x            =  window_x / (window_width / 2.0);
           update_pos = true;
        }
        if ( xev.type == KeyPress )   quit = true;
     }
     render();   // now we finally put something on the screen
     if ( ++num_frames % 100 == 0 ) {
        gettimeofday( &t2, &tz );
        float dt  =  t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) * 1e-6;
        cout << "fps: " << num_frames / dt << endl;
        num_frames = 0;
        t1 = t2;
     }

// usleep( 1000*10 );

  }


  ////  cleaning up...
  eglDestroyContext ( egl_display, egl_context );
  eglDestroySurface ( egl_display, egl_surface );
  eglTerminate      ( egl_display );
  XDestroyWindow    ( x_display, win );
  XCloseDisplay     ( x_display );
  return 0;

} </source>