CG programming (OpenGL)

Source: Internet
Author: User
Original Note: B Alex d 'Angelo (alexz@FusionIndustries.com) Translation: 文 without my consent, cannot be used for commercial publishing purposes. This article describes how to add advanced coloring of vertices and fragments to your existing graphics program. Using CG coloring language will make your work easier. In programming, you can call some existing CG functions to complete your work. Of course, you can also write some color devices when you have learned deeply. The "the CG tutorial" written by Fernando and kilgard is the most valuable reference. You can download it from the NVIDIA website. I. OverviewThe program in this article draws a cube in the screen power by combining OpenGL and glut, and adds the CG coloring program code to the program. Listing1 contains the complete original program code. The CG part is marked in bold. This program runs through the full text. Listing2 is a CG Vertex coloring code. 2. Establish a CG programming environmentBefore proceeding to CG programming, first download CG toolkit "CG toolkit", you can find in the following url: http://developer.nvidia.com/CG, please pay attention to see whether your graphics card supports Vertex coloring programming. Install the CG toolkit. To enable it to work in Visual C ++, you can use either of the following methods. First, copy the content in the CG header file and library file to the Visual C ++ header file and the library file folder respectively. From: C:/program files/NVIDIA Corporation/CG/libto: C:/program files/Microsoft Visual Studio/vc98/lib from: C: /program files/NVIDIA Corporation/CG/includeto: C:/program files/Microsoft Visual Studio/vc98/include the second method is to add a search path to the VC Compiler: tools-> options-> projects-> "directiress" C:/program files/NVIDIA Corporation/CG/includec: /program files/NVIDIA Corporation/CG/lib although our program needs to connect "CG. lib "" cggl. lib "These two library files, You can write it to the connection path: "properties-> linker-> input". Add the following code at the beginning of the program: # ifdef _ msc_ver # pragma comment (Lib, "CG. lib ") # pragma comment (Lib," cggl. lib ") # endif 3. CG programming details in order to use the CG shader, we must create a coloring context (cgcontext) in the program. One program requires only one coloring context. You need to create a cgprogram for each colorant, And you can specify a separate cgprofile for each colorant ), cgprofile is used to show CG how to select the method that best suits your video card to color the vertex or fragment. The shader can be loaded wherever you want to use it. During loading, you only need to pass the program a name of the colorant function entry or the name of the colorant file. In this example, the shader is loaded before the drawing loop, and to meet the needs of various graphics cards, we specify a basic profile for the shader, "cg_profile_vp20 ". 1. Set the variables to be used by the shader.First, include the CG header file in your program: # include <CG/CG. h> # include <CG/cggl. h> then, add some variables used to save the sprite entry address: static cgcontext context = NULL; static cgprogram vertexprogram = NULL; and some address variables of the coloring parameters, after the colorator is initialized, these address variables are bound to specific parameters by using "cgparameters. Static cgparameter kdparam = NULL; static cgparameter modelviewprojparam = NULL; static cgparameter vertexcolorparam = NULL; finally, specify the profile used for vertex coloring: static cgprofile vertexprofile = cg_profile_vp20; 2. initialize CGIn the program, initialize OpenGL, and then initialize CG. First, you need to create a color context. A program can have a color context, and all the colored devices used will share the context. Context = cgcreatecontext ();
Next, you can add a vertex shader to the coloring context by specifying the file name and the type of the shader (vertex coloring here) for the context. Vertexprogram = cgcreateprogramfromfile (context, cg_source, "vertexshader. CG", vertexprofile, null,
Null );
Only after the vertex shader is successfully created can the code of the shader be truly loaded into the program. At the same time, various coloring parameter addresses are finally bound with the parameters in the shader. In the subsequent programs, you can freely use and change the content of these parameters. As shown in the example, variables such as the reflected light color (kdparam), vertexcolorparam, and modelviewproj can be changed. After the main cycle of the drawing is completed, all the resources occupied by the coloring tool should be released in time. In CG, two functions are provided: cgdestroyprogram (); and cgdestroycontext (); it makes it easier for us to complete this task. 3. Drawing cycleAfter entering the drawing loop, the colorant will be called before the actual drawing. After the drawing ends, it should be disabled. This concept is similar to glbegin (); and glend ();. Actually, the initial work of CG cannot be called between glbegin (); and glend. Before all plotting starts, we call the cgglbindprogram () function to associate the coloring code with the OpenGL drawing code, and then call cgglableprofile (); function to specify whether the CG program performs Vertex coloring or fragment coloring. Then we can use the cgglsetparamter * (); function to pass or use the parameters in the shader. After all the plotting work is complete, we should immediately call cggldisableprofile (); to stop the use of the shader. The color of the vertex can be changed at any time. For example, the color of the vertex of a cube can be set through the function cgglsetparameter3f (vertexcolorparam, 0.0, 1.0, 0.00. Now that we know how to use a shader in a drawing loop, it is easy to extend it to the situation where multiple colorants are used in a drawing loop, simply bind the coloring package to the outer layer of the drawing code. Example: void draw () {Program (Program); cgglableprofile (profile); drawing_code () cggldisableprofile (profile); cgglbindprogram (program2); cgglableprofile (profile2); drawing_code2 () cggldisableprofile (profile2 );} Iv. ConclusionNow we have learned how to add the coloring code to our existing programs. In. Listing 1: Hellocg. cusing CG with your programs. CG specific callare in bold. heavily based on the runtime_oglproject In the CG toolkit.
/* Minimalist program for using shaders, with no error checking */#ifdef _MSC_VER#pragma comment ( lib , "cg.lib" )#pragma comment ( lib , "cgGL.lib" )#endif#include <math.h>#include <stdio.h>#include <stdlib.h>#ifdef __APPLE__#include <GLUT/glut.h>#else#include <GL/glut.h>#endif#include <Cg/cg.h>#include <Cg/cgGL.h>/******************************************************************************//*** Static Data ***//******************************************************************************//* New Cg global variables */static CGcontext Context = NULL;static CGprogram VertexProgram = NULL;static CGparameter KdParam = NULL;static CGparameter ModelViewProjParam = NULL;static CGparameter VertexColorParam = NULL;#ifdef __APPLE__static CGprofile VertexProfile = CG_PROFILE_ARBVP1;#elsestatic CGprofile VertexProfile = CG_PROFILE_VP20;#endif/* End new Cg global variables */GLfloat CubeNormals[6][3] ={{-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0},{0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0}};GLint CubeFaces[6][4] ={{0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4},{4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3}};GLfloat CubeVertices[8][3]; /******************************************************************************/static void DrawCube( void){int i;cgGLBindProgram(VertexProgram);/** Set various uniform parameters including the ModelViewProjection* matrix for transforming the incoming position into HPOS.*/if (KdParam != NULL)cgGLSetParameter4f(KdParam, 1.0, 1.0, 0.0, 1.0);/* Set the concatenate modelview and projection matrices */if (ModelViewProjParam != NULL)cgGLSetStateMatrixParameter(ModelViewProjParam,CG_GL_MODELVIEW_PROJECTION_MATRIX,CG_GL_MATRIX_IDENTITY);cgGLEnableProfile(VertexProfile);/** Create cube with per-vertex varying attributes*/for(i = 0; i < 6; i++){glBegin(GL_QUADS);{glNormal3fv(&CubeNormals[i][0]);cgGLSetParameter3f(VertexColorParam, 1.0, 0.0, 0.0);glVertex3fv(&CubeVertices[CubeFaces[i][0]][0]);cgGLSetParameter3f(VertexColorParam, 0.0, 1.0, 0.0);glVertex3fv(&CubeVertices[CubeFaces[i][1]][0]);cgGLSetParameter3f(VertexColorParam, 0.0, 0.0, 1.0);glVertex3fv(&CubeVertices[CubeFaces[i][2]][0]);cgGLSetParameter3f(VertexColorParam, 1.0, 1.0, 1.0);glVertex3fv(&CubeVertices[CubeFaces[i][3]][0]);}glEnd();}cgGLDisableProfile(VertexProfile);}static void Display(void){glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);DrawCube();glutSwapBuffers();}static void InitializeCube( GLfloat v[8][3]){/* Setup cube vertex data. */v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1;v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1;v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1;v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1;v[0][2] = v[3][2] = v[4][2] = v[7][2] = 1;v[1][2] = v[2][2] = v[5][2] = v[6][2] = -1;}static void InitializeGlut(int *argc, char *argv[]){glutInit(argc, argv);glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);glutCreateWindow(argv[0]);glutDisplayFunc(Display);InitializeCube(CubeVertices);/* Use depth buffering for hidden surface elimination. */glEnable(GL_DEPTH_TEST);/* Setup the view of the cube. */glMatrixMode(GL_PROJECTION);gluPerspective( /* field of view in degree */ 40.0,/* aspect ratio */ 1.0,/* Z near */ 1.0, /* Z far */ 10.0);glMatrixMode(GL_MODELVIEW);gluLookAt(0.0, 0.0, 5.0, /* eye is at (0,0,5) */0.0, 0.0, 0.0, /* center is at (0,0,0) */0.0, 1.0, 0.); /* up is in positive Y direction *//* Adjust cube position to be asthetic angle. */glTranslatef(0.0, 0.0, -1.0);#if 1glRotatef(60, 1.0, 0.0, 0.0);glRotatef(-20, 0.0, 0.0, 1.0);#endif}int main(int argc, char *argv[]){InitializeGlut(&argc, argv);/* Create one context which all shaders will use */Context = cgCreateContext();/* Adds shader to the context */VertexProgram = cgCreateProgramFromFile(Context,CG_SOURCE, "vertexShader.cg" ,VertexProfile,NULL, NULL);if (VertexProgram != NULL){/* Vertex shader only needs to be loaded once */cgGLLoadProgram(VertexProgram);/* Bind parameters to give access to variables in the shader */KdParam = cgGetNamedParameter(VertexProgram, "Kd" );ModelViewProjParam = cgGetNamedParameter(VertexProgram, "ModelViewProj" );VertexColorParam = cgGetNamedParameter(VertexProgram, "IN.VertexColor" );}glutMainLoop();cgDestroyProgram(VertexProgram);cgDestroyContext(Context);return 0;}
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //// Listing 2: Vertexshader. cgcg vertex shader code written. heavily based on the runtime_ogl project in the CG toolkit.
struct appdata{float4 position : POSITION;float3 normal : NORMAL;float3 color : DIFFUSE;float3 VertexColor : SPECULAR;};struct vfconn{float4 HPOS : POSITION;float4 COL0 : COLOR0;};vfconn main(appdata IN,uniform float4 Kd,uniform float4x4 ModelViewProj){vfconn OUT;OUT. HPOS = mul (ModelViewProj, IN.position);OUT. COL0 .xyz = Kd.xyz * IN.VertexColor.xyz;OUT. COL0 .w = 1.0;return OUT;} // main

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.