OpenGL (8)-glsl

Source: Internet
Author: User
Introduction

With the development of graphics hardware, rendering pipelines are constantly evolving from fixed to non-editable to programmable and smoother directions. More and more GPU-based programming languages are emerging, such as CG, Cuda, and various coloring languages.

Today, we will introduce the very close combination of glsl (OpenGL shading language) with OpenGL. Through OpenGL APIs, we can plot elements, transform graphics, and so on. When it does not change the basic rendering pipeline. Using glsl in OpenGL enables you to convert fixed functional phases in the rendering pipeline into programmable ones.

Programming Environment: ubuntu12.04 32bit gtx.pdf

Glsl Introduction

OpenGL shading language (glsl-OpenGL shading Language) is a language used to color programming in OpenGL, that is, a short custom program written by developers, they are executed on the graphics card's GPU (Graphic processor unit graphics processing unit) instead of a portion of the Fixed rendering pipeline. For example, view conversion and projection conversion. The glsl (GL shading language) shader code is divided into two parts: vertex shader and fragment ), sometimes there is a geometry shader ). The Vertex coloring tool is responsible for running Vertex coloring. It can obtain the current OpenGL
The glsl built-in variables are passed. It has the following features:

1. It is an advanced procedural language;

2. As part of the OpenGL standard, it means open source and cross-platform;

3. syntax and Process Control Based on C and C ++;

4. Operations on Vectors and matrices are supported;

5. More Strict variable control than C and C ++;

6. Use variables to process input and output rather than reading and writing documents;

7. There is no limit on the shader length and there is no need to query it.

Why use OpenGL shader?

1. Increase the material's real material experience-stone, grass, wood, etc;

2. Increase the actual material perception of the illumination effect-surface light source, soft shadow, and so on;

3. Advanced rendering effects-Global lighting, light tracing, and so on;

4. Non-real materials-simulate the paint brush effect, Pen Painting effect, and so on;

5. Phase Paster-dynamically generate 2D and 3D textures instead of static images;

6. Image Processing-convolution, masks, and complex Mixing;

7. Dynamic Effects-key frame interpolation, particle system, and animation;

8. Programmable anti-sample method;

9. General computing-sorting, mathematical modeling, fluid computing;

These features may be implemented when OpenGL is used, but there are some limitations. Now, with shader, We can significantly increase the rendering speed through the hardware acceleration of the video card, at the same time, CPU can be liberated.

Write a simple shader

First, let's take a look at the computer's OpenGL environment and terminal operation:

Glxinfo | grep OpenGL

The SDL-based OpenGL has been installed (refer to here: SDL getting started). Next we need to install the OpenGL extension library.

Sudo apt-Get install glew-utils libglew1.6

Draw a simple rectangle this time.

Create a basic. Vert in the project folder as vertex shader.

#version 400in vec3 VertexPosition;in vec3 VertexColor;out vec3 Color;void main(){Color = VertexColor;gl_Position = vec4( VertexPosition, 1.0);}

· In-for input parameters
· Out-for outputs of the function. The returnstatement is also an option for sending the result of a function.
· Inout-for parameters that are both input andoutput of a function (the new glsl version seems to have been abolished)

Create a basic. Frag as the fragment shader.

#version 400void main(void){gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);}

Create main. C with the following code:

/*****************************************************************************Copyright: 2013, ustc All rights reserved.contact:k283228391@126.comFile name: main.cDescription:Using opengl shading language in SDL.Author:Silang QuanVersion: 1.0Date: 2013.7.30*****************************************************************************/#include <SDL/SDL.h>#include <GL/glew.h>#include <GL/gl.h>#include <GL/glu.h>#include <stdio.h>#include <stdlib.h>const int SCREEN_WIDTH = 800;const int SCREEN_HEIGHT =800;const int SCREEN_BPP = 32;SDL_Surface *screen;//Whether the window is windowed or notbool windowed;//Whether the window is finebool windowOK;//Handler for GLSL programGLuint programHandle;GLuint vShader;GLuint fShader;void quit( int code ){    SDL_Quit( );    /* Exit program. */    exit( code );}char *textFileRead(char *fn) {     FILE *fp;    char *content = NULL;     int count=0;     if (fn != NULL) {        fp = fopen(fn,"rt");         if (fp != NULL) {       fseek(fp, 0, SEEK_END);      count = ftell(fp);      rewind(fp);             if (count > 0) {                content = (char *)malloc(sizeof(char) * (count+1));                count = fread(content,sizeof(char),count,fp);                content[count] = '\0';            }            fclose(fp);        }    }    return content;}void toggle_fullscreen(){//If the screen is windowedif( windowed == true ){//Set the screen to fullscreenscreen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL|SDL_RESIZABLE| SDL_FULLSCREEN );//If there's an errorif( screen == NULL ){windowOK = false;return;}//Set the window state flagwindowed = false;}//If the screen is fullscreenelse if( windowed == false ){//Window the screenscreen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL|SDL_RESIZABLE );//If there's an errorif( screen == NULL ){windowOK = false;return;}//Set the window state flagwindowed = true;}}void handleKeyEvent( SDL_keysym* keysym ){    switch( keysym->sym ){    case SDLK_ESCAPE:        quit( 0 );        break;    case SDLK_SPACE:        break;    case SDLK_F1:toggle_fullscreen();break;    default:        break;    }}void resizeGL(int width,int height){    if ( height == 0 )    {        height = 1;    }    //Reset View    glViewport( 0, 0, (GLint)width, (GLint)height );    //Choose the Matrix mode    glMatrixMode( GL_PROJECTION );    //reset projection    glLoadIdentity();    //set perspection    gluPerspective( 45.0, (GLfloat)width/(GLfloat)height, 0.1, 100.0 );    //choose Matrix mode    glMatrixMode( GL_MODELVIEW );    glLoadIdentity();}void handleEvents(){    // Our SDL event placeholder.    SDL_Event event;    //Grab all the events off the queue.    while( SDL_PollEvent( &event ) ) {        switch( event.type ) {        case SDL_KEYDOWN:            // Handle key Event            handleKeyEvent( &event.key.keysym );            break;        case SDL_QUIT:            // Handle quit requests (like Ctrl-c).            quit( 0 );            break;        case SDL_VIDEORESIZE://Handle resize event            screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 16,                                      SDL_OPENGL|SDL_RESIZABLE);            if ( screen )            {                resizeGL(screen->w, screen->h);            }            break;        }    }}void initSDL(int width,int height,int bpp,int flags){    // First, initialize SDL's video subsystem.    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )    {        fprintf( stderr, "Video initialization failed: %s\n",                 SDL_GetError( ) );        quit( 1 );    }    atexit(SDL_Quit);//Set some Attribute of OpenGL in SDL    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );    //Set the video mode    screen= SDL_SetVideoMode( width, height, bpp,flags);    if(!screen )    {        fprintf( stderr, "Video mode set failed: %s\n",SDL_GetError( ) );        quit( 1 );    windowed=false;}else windowed=true;    resizeGL(screen->w, screen->h);    //Set caption    SDL_WM_SetCaption( "OpenGL Shading Language Test", NULL );    }void initShader(){vShader = glCreateShader( GL_VERTEX_SHADER );fShader = glCreateShader( GL_FRAGMENT_SHADER );printf("Here\n");if(0 == vShader || 0 == fShader){fprintf(stderr, "Error creating vertex shader.\n");quit(1);}GLchar* vShaderCode = textFileRead("basic.vert");GLchar* fShaderCode = textFileRead("basic.frag");const GLchar* vCodeArray[1] = {vShaderCode};const GLchar* fCodeArray[1] = {fShaderCode};glShaderSource(vShader, 1, vCodeArray, NULL);glShaderSource(fShader, 1, fCodeArray, NULL);glCompileShader(vShader);glCompileShader(fShader);free(vShaderCode);free(fShaderCode);//const GLchar* codeArray[] = {shaderCode};//Check the compile resultGLint logLen;glGetShaderiv(vShader, GL_INFO_LOG_LENGTH, &logLen);if(logLen > 0){char *log = (char *)malloc(logLen);GLsizei written;glGetShaderInfoLog(vShader, logLen, &written, log);printf("Shader compile error log: %s\n",log);free(log);}programHandle = glCreateProgram();if(0 == programHandle){fprintf(stderr, "Error creating programHandle.\n");quit(1);}glAttachShader(programHandle, vShader);glAttachShader(programHandle, fShader);glLinkProgram(programHandle);//glUseProgram(programHandle);}void freeShader(){glDetachShader(programHandle, fShader);glDetachShader(programHandle, vShader);glDeleteShader(fShader);glDeleteShader(vShader);//glDetachShader(fShader);//glDetachShader(vShader);//glDetachShader(programHandle);}void renderGL(){/* These are to calculate our fps */    static GLint T0     = 0;static GLint Frames = 0;    // Clear the color and depth buffers.    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );    // We don't want to modify the projection matrix. */    glMatrixMode( GL_MODELVIEW );    glLoadIdentity( );    // Move down the z-axis.    glTranslatef( 0.0, 0.0, -5.0 );//Draw a square    glUseProgram(programHandle);    glBegin(GL_QUADS);            glVertex2f(-0.5f, -0.5f);            glVertex2f( 0.5f, -0.5f);            glVertex2f( 0.5f,  0.5f);            glVertex2f(-0.5f,  0.5f);    glEnd();        // Unbind shader    glUseProgram(0);    SDL_GL_SwapBuffers( );        /* Gather our frames per second */    Frames++;    {GLint t = SDL_GetTicks();if (t - T0 >= 5000) {    GLfloat seconds = (t - T0) / 1000.0;    GLfloat fps = Frames / seconds;    printf("%d frames in %g seconds = %g FPS\n", Frames, seconds, fps);    T0 = t;    Frames = 0;}    }}void initGL( int width, int height ){    float ratio = (float) width / (float) height;    // Our shading model--Gouraud (smooth).    glShadeModel( GL_SMOOTH );    // Set the clear color.    glClearColor( 0, 0, 0, 0 );    // Setup our viewport.    glViewport( 0, 0, width, height );    //Change to the projection matrix and set our viewing volume.    glMatrixMode( GL_PROJECTION );    glLoadIdentity();    gluPerspective( 60.0, ratio, 1.0, 100.0 );}int main( int argc, char* argv[] ){// Color depth in bits of our window.int flags= SDL_OPENGL|SDL_RESIZABLE;//Set the SDLinitSDL(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,flags);if(glewInit() != GLEW_OK) exit(EXIT_FAILURE);//Init vertext shaderinitShader();//Set the OpenGLinitGL(SCREEN_WIDTH, SCREEN_HEIGHT );    //main loop    while(true){        /* Process incoming events. */        handleEvents( );        /* Draw the screen. */        renderGL( );    }    // Free Shader    freeShader();    return 0;}

It mainly adds several shader functions. initshader is used for Shader initialization, freeshader is used to delete shader and release memory. Before using shader, you also need to call glewinit to initialize glew.

Terminal compilation command:

G ++ main. C-o main-lsdl-lgl-lglu-lglew


Several related APIs are explained.

GLuint glCreateShader(GLenum shaderType);Parameter:shaderType – GL_VERTEX_SHADER, GL_GEOMETRY_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, or GL_FRAGMENT_SHADER.Return Value:the shader handler

void glShaderSource(GLuint shader, int numOfStrings, const char **strings, int *lengthOfStrings);Parameters:shader – the handler to the shader.numOfStrings – the number of strings in the array.strings – the array of strings.lengthOfStrings – an array with the length of each string, or NULL, meaning that the strings are NULL terminated.

void glCompileShader(GLuint shader);Parameters:shader – the handler to the shader.

void glUseProgram(GLuint program); Installs a program object as part of current rendering stateParameters:programSpecifies the handle of the program object whose executables are to be used as part of current rendering state.

...

The entire OpenGL program execution process is as follows:

For more functions, see OpenGL reference-http://www.opengl.org/sdk/docs/man/

Reference

OpenGL 4.0 shading language cookbook

Glsl core tutorial-creating a shader-http://www.lighthouse3d.com/tutorials/glsl-core-tutorial/creating-a-shader/

Hello glsl http://sindney.com/blog/posts/hello-glsl/

OpenGL reference-http://www.opengl.org/sdk/docs/man/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.