NeHe OpenGL Lesson47 - CG Vertex Shader
This samples us how to apply Cg vertex shader in OpenGL. Shader is a kind of short c-like code that could run on the GPU. One the one hand, we could get much flexibility while rendering our-own visual effect. This will keep us away from hard understanding OpenGL render states settings. On the other hand, we could move some work form the CPU to GPU, this could be better for us balance the whole workload between CPU and GPU.
The Usage of CG Vertex Shader
The workflow to use cg vertex shader almost the same as GLSL or HLSL. Usually, the general steps as following:
1) Setup the shader context: check the supported version number, check whether video card support shader or not, create some container to hold all shaders and so on;
2) Compile the shader from source code;
3) Get the shader program from the compiled result;
4) Retrieve the shader parameters from shader program;
5) While rendering, bind or set shader program, and set the shader parameters;
6) Release shader program resource while shut down;
Set up Cg & Get the latest Vertex Profile
cgContext = cgCreateContext();
...
cgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
Compile the Cg shader Source code
cgGLSetOptimalOptions(cgVertexProfile); cgVertexProgram = cgCreateProgramFromFile(cgContext, CG_SOURCE, "CG/Wave.cg", cgVertexProfile, "main", 0);
Load the Shader Program & Retrieve the Shader Parameter
cgGLLoadProgram(cgVertexProgram); position = cgGetNamedParameter(cgVertexProgram, "IN.position");
Draw with Shader Program
cgGLEnableProfile(cgVertexProfile); // Bind Our Vertex Program To The Current State cgGLBindProgram(cgVertexProgram); cgGLSetParameter4f(color, 0.5f, 1.0f, 0.5f, 1.0f); // Submit verterx data here ... cgGLDisableProfile(cgVertexProfile);
Release Cg Shader Program
cgDestroyProgram(cgVertexProgram);
cgDestroyContext(cgContext);
The full source code could be found here.