OpenGL立方体在世界坐标系中_缩放_旋转_平移_顶点片源着色器_光照作用
来源:互联网 发布:修改照片拍摄时间软件 编辑:程序博客网 时间:2024/06/11 18:55
在上一篇的基础上加了光照。并把原来的颜色改成环境光分量的选择。
工程http://download.csdn.net/detail/u014646950/9477259
工程里面和exe在同一目录的.glsl忘记更改了。
//// 绘制一个旋转的OpenGL立方体在世界坐标系中_缩放_旋转_平移_顶点片源着色器_光照作用// 使用空闲回调函数增加旋转的角度// 立方体的旋转角度被发送到用于实现立方体旋转的顶点着色器中#include "Angel.h"#pragma comment(lib, "glew32.lib")typedef Angel::vec4 color4;typedef Angel::vec4 point4;const int NumVertices = 36; //(6 faces)(2 triangles/face)(3 vertices/triangle)point4 points[NumVertices];vec3 normals[NumVertices];//法向量标记// Vertices of a unit cube centered at origin, sides aligned with axespoint4 vertices[8] = {point4(-0.5, -0.5, 0.5, 1.0),point4(-0.5, 0.5, 0.5, 1.0),point4(0.5, 0.5, 0.5, 1.0),point4(0.5, -0.5, 0.5, 1.0),point4(-0.5, -0.5, -0.5, 1.0),point4(-0.5, 0.5, -0.5, 1.0),point4(0.5, 0.5, -0.5, 1.0),point4(0.5, -0.5, -0.5, 1.0)}; // Array of rotation angles (in degrees) for each coordinate axis//enum { Xaxis = 0, Yaxis = 1, Zaxis = 2, NumAxes = 3 };//enum { Xdist = 0, Ydist = 1, Zdist = 2, NumAxes1 = 3 };color4 gr = color4(1.0, 1.0, 1.0, 1.0); color4 onecolor = color4(1.0, 0.0, 0.0, 1.0);color4 light_ex;int Axi = 0;//Xaxis;GLfloat Thet[3] = { 0.0, 0.0, 0.0 };//GLfloat Atha[3] = { 0.0, 0.0, 0.0 };GLfloat Disx = 0;GLfloat Dis = 0;GLfloat fd = 1;GLuint thet; // The location of the "theta" shader uniform variableGLuint atha;GLuint direct;GLuint f;GLuint vam;//----------------------------------------------------------------------------// quad generates two triangles for each face and assigns colors// to the verticesint Index = 0;voidquad(int a, int b, int c, int d){vec4 u = vertices[b] - vertices[a];vec4 v = vertices[c] - vertices[b];vec3 normal = normalize(cross(u, v));//normalize叉乘得到法向量normals[Index] = normal; points[Index] = vertices[a]; Index++;normals[Index] = normal; points[Index] = vertices[b]; Index++;normals[Index] = normal; points[Index] = vertices[c]; Index++;normals[Index] = normal; points[Index] = vertices[a]; Index++;normals[Index] = normal; points[Index] = vertices[c]; Index++;normals[Index] = normal; points[Index] = vertices[d]; Index++;}//----------------------------------------------------------------------------// generate 12 triangles: 36 vertices and 36 colorsvoidcolorcube(){quad(1, 0, 3, 2);quad(2, 3, 7, 6);quad(3, 0, 4, 7);quad(6, 5, 1, 2);quad(4, 5, 6, 7);quad(5, 4, 0, 1);}//----------------------------------------------------------------------------// OpenGL initializationvoidinit(){colorcube();// Create a vertex array objectGLuint vao;glGenVertexArrays(1, &vao);glBindVertexArray(vao);// Create and initialize a buffer objectGLuint buffer;glGenBuffers(1, &buffer);glBindBuffer(GL_ARRAY_BUFFER, buffer);glBufferData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(normals),NULL, GL_STATIC_DRAW);glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(points), points);glBufferSubData(GL_ARRAY_BUFFER, sizeof(points), sizeof(normals), normals);// Load shaders and use the resulting shader programGLuint program = InitShader("vshader.glsl", "fshader.glsl");glUseProgram(program);// set up vertex arraysGLuint vPosition = glGetAttribLocation(program, "vPosition");glEnableVertexAttribArray(vPosition);glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0));GLuint vNormal = glGetAttribLocation(program, "vNormal");glEnableVertexAttribArray(vNormal);glVertexAttribPointer(vNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(sizeof(points)));//初始化光照参数la,ld,ls环境,漫反射,镜面反射point4 light_position(0.0, 0.0, 2.0,-0.0);//color4 light_ambient(1.0,0.0,0.0,1.0);//R红_G绿_B蓝color4 light_diffuse(1.0, 1.0, 1.0, 1.0);color4 light_specular(1.0, 1.0, 1.0, 1.0);color4 material_ambient(1.0, 0.0, 1.0, 1.0);color4 material_diffuse(1.0, 0.8, 0.0, 1.0);color4 material_specular(1.0, 0.8, 0.0, 1.0);float material_shininess = 20.0;//高光系数 高金属 低塑料light_ex = material_ambient;//color4 ambient_product = light_ambient*material_ambient;color4 diffuse_product = light_diffuse*material_diffuse;color4 specular_product = light_specular*material_specular;glUniform4fv(glGetUniformLocation(program, "DiffuseProduct"), 1, diffuse_product);glUniform4fv(glGetUniformLocation(program, "SpecularProduct"), 1, specular_product);glUniform4fv(glGetUniformLocation(program, "LightPosition"), 1, light_position);glUniform1f(glGetUniformLocation(program,"Shininess"),material_shininess);vam = glGetUniformLocation(program, "AmbientProduct");thet = glGetUniformLocation(program, "theta");atha = glGetUniformLocation(program, "athat");direct = glGetUniformLocation(program, "direct");f = glGetUniformLocation(program, "ff");glEnable(GL_DEPTH_TEST);///开启深度缓存测试glEnable(GL_CULL_FACE);///启动多边形剔除功能//glOrtho(1.0, 0.0, 0.0, 1.0, 0.0, 1.0);}//----------------------------------------------------------------------------voiddisplay(void){glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//glMatrixMode(GL_PROJECTION); //glMatrixMode(GL_MODELVIEW);//glLoadIdentity(); //gluLookAt(1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.1, 0.0);glUniform4fv(vam, 1, light_ex*onecolor);glUniform3fv(thet, 1, Thet);glUniform1f(atha, Disx);glUniform1f(direct, Dis);//传递单个的 glUniform1f(f, fd); glDrawArrays(GL_TRIANGLES, 0, NumVertices);glClearColor(gr[0], gr[1], gr[2], gr[3]);glFlush(); }void ProcessMenu(int value){if (value == 0)exit(0);if (value == 100){gr = vec4(1.0f, 1.0f, 1.0f, 1.0f);onecolor = vec4(1.0, 0.0, 1.0, 1.0);}else{switch (value){case 21:gr = vec4(0.75f, 0.0f, 1.0f, 1.0f); break;case 22:gr = vec4(0.75f, 0.75f, 1.0f, 1.0f); break;case 23:gr = vec4(1.75f, 1.75f, 0.75f, 1.0f); break;case 24:gr = vec4(1.75f, 1.0f, 1.55f, 1.0f); break;case 25:gr = vec4(0.0f, 1.0f, 0.75f, 0.0f); break;case 1:onecolor = color4(0.0, 0.0, 0.0, 1.0); break;//黑色case 2:onecolor = color4(0.0, 0.0, 1.0, 1.0); break;//蓝色case 3:onecolor = color4(1.0, 0.0, 1.0, 1.0); break;//品红色case 4:onecolor = color4(0.0, 1.0, 1.0, 1.0); break;//青色}}glutSwapBuffers();glutPostRedisplay();}//----------------------------------------------------------------------------voidkeyboard(unsigned char key, int x, int y){ switch (key) {case 'x': Axi = 0; break; //Xaxis; break;case 'y': Axi = 1; break;//Yaxis; break;case 'z': Axi = 2; break;//Zaxis; break;选择对应的x,y,z旋转角度来变化case 'f':fd += 0.1; break;//Xdist; break;case 's':fd -= 0.1; break;//Ydist; break;case 033: // Escape Keycase 'q': case 'Q':exit(EXIT_SUCCESS);break;}if (fd == 0)fd = 0.1;}void SpecialKeys(int key, int x, int y){ switch (key) {case GLUT_KEY_UP:Dis += 0.01; break;case GLUT_KEY_DOWN:Dis -= 0.01; break;//Ydist; break;case GLUT_KEY_LEFT:Disx -= 0.01; break; case GLUT_KEY_RIGHT:Disx += 0.01; break;//Xdist; break;case 033: // Escape Keycase 'q': case 'Q':exit(EXIT_SUCCESS);break;}}//----------------------------------------------------------------------------//----------------------------------------------------------------------------voididle(void){Thet[Axi] += 0.01;if (Thet[Axi] > 360.0) {Thet[Axi] -= 360.0;}glutSwapBuffers();glutPostRedisplay();}//----------------------------------------------------------------------------intmain(int argc, char **argv){ glutInit(&argc, argv);glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);glutInitWindowSize(512, 512);glutInitContextVersion(3, 1);//这里在舍友的电脑上用3,2可以用,在我的电脑上会出现//freeglut(dll地址):unableto create OpenGL3.2 context(flags 0, profile 1)//我改成3,1就可以了。不知道会不会是版本问题。这里用的是比较旧的版本freeglut。glutInitContextProfile(GLUT_CORE_PROFILE);glutCreateWindow("Color Cube");glewExperimental = true;glewInit(); int nGlutColorMenu1 = glutCreateMenu(ProcessMenu);glutAddMenuEntry("black", 1);glutAddMenuEntry("blue", 2);glutAddMenuEntry("magenta", 3);glutAddMenuEntry("cyan", 4);int nGlutColorMenu2 = glutCreateMenu(ProcessMenu);glutAddMenuEntry("background1", 21);glutAddMenuEntry("background2", 22);glutAddMenuEntry("background3", 23);glutAddMenuEntry("background4", 24);glutAddMenuEntry("background5", 25);int nGlutColorMenu3 = glutCreateMenu(ProcessMenu);glutAddMenuEntry("return", 100);int nGlutColorMenu = glutCreateMenu(ProcessMenu);glutAddSubMenu("coclor", nGlutColorMenu1);glutAddSubMenu("background", nGlutColorMenu2);glutAddSubMenu("return", nGlutColorMenu3);glutAttachMenu(GLUT_RIGHT_BUTTON);init();glutDisplayFunc(display);glutSpecialFunc(SpecialKeys);glutKeyboardFunc(keyboard);//glutMouseFunc(mouse);glutIdleFunc(idle); glutMainLoop();return 0;}
#version 150in vec4 vPosition;in vec3 vNormal;out vec4 color;uniform vec4 AmbientProduct,DiffuseProduct,SpecularProduct;uniform vec4 LightPosition;uniform float Shininess;uniform vec3 theta;uniform float athat;uniform float direct;uniform float ff;void main() { vec3 angles = radians( theta ); vec3 c = cos( angles ); vec3 s = sin( angles ); mat4 rx = mat4( 1.0, 0.0, 0.0, 0.0, 0.0, c.x, s.x, 0.0, 0.0, -s.x, c.x, 0.0, 0.0, 0.0, 0.0, 1.0 ); mat4 ry = mat4( c.y, 0.0, -s.y, 0.0, 0.0, 1.0, 0.0, 0.0, s.y, 0.0, c.y, 0.0, 0.0, 0.0, 0.0, 1.0 ); // Workaround for bug in ATI driver ry[1][0] = 0.0; ry[1][1] = 1.0; mat4 rz = mat4( c.z, s.z, 0.0, 0.0, -s.z, c.z, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ); // Workaround for bug in ATI driver rz[2][2] = 1.0; //color = vColor; mat4 t=mat4(1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,athat,direct,0.0,1.0); mat4 sf=mat4(ff,0.0,0,0,0.0,ff,0.0,0.0,0.0,0.0,ff,0.0,0.0,0.0,0.0,1.0); mat4 modeview=t*rx*rz*ry;vec3 pos=(modeview*vPosition).xyz;vec3 L=normalize(LightPosition.xyz-pos);vec3 E=normalize(-pos);vec3 H=normalize(L+E);vec3 N=normalize(modeview*vec4(vNormal,0.0)).xyz;vec4 ambient=AmbientProduct; float Kd=max(dot(L,N),0.0);vec4 diffuse=Kd*DiffuseProduct; float Ks=pow(max(dot(N,H),0.0),Shininess); vec4 specular=Ks*SpecularProduct; if(dot(L,N)<0.0) specular=vec4(0.0,0.0,0.0,1.0); gl_Position =modeview*sf*vPosition;color=ambient+diffuse+specular;color.a=1.0;}
#version 150in vec4 color;out vec4 fColor;void main() { fColor = color;}
#include "Angel.h"namespace Angel {// Create a NULL-terminated string by reading the provided filestatic char*readShaderSource(const char* shaderFile){ //FILE* fp = fopen(shaderFile, "r");//由于vs甚么安全性的原因,不让使用fopen,用下面的fopen_s代替;FILE *fp;fopen_s(&fp, shaderFile, "r"); if ( fp == NULL ) { return NULL; } fseek(fp, 0L, SEEK_END); long size = ftell(fp); fseek(fp, 0L, SEEK_SET); char* buf = new char[size + 1]; fread(buf, 1, size, fp); buf[size] = '\0'; fclose(fp); return buf;}// Create a GLSL program object from vertex and fragment shader filesGLuintInitShader(const char* vShaderFile, const char* fShaderFile){ struct Shader {const char* filename;GLenum type;GLchar* source; } shaders[2] = {{ vShaderFile, GL_VERTEX_SHADER, NULL },{ fShaderFile, GL_FRAGMENT_SHADER, NULL } }; GLuint program = glCreateProgram(); for ( int i = 0; i < 2; ++i ) {Shader& s = shaders[i];s.source = readShaderSource( s.filename );if ( shaders[i].source == NULL ) { std::cerr << "Failed to read " << s.filename << std::endl; exit( EXIT_FAILURE );}GLuint shader = glCreateShader( s.type );glShaderSource( shader, 1, (const GLchar**) &s.source, NULL );glCompileShader( shader );GLint compiled;glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );if ( !compiled ) { std::cerr << s.filename << " failed to compile:" << std::endl; GLint logSize; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize ); char* logMsg = new char[logSize]; glGetShaderInfoLog( shader, logSize, NULL, logMsg ); std::cerr << logMsg << std::endl; delete [] logMsg; exit( EXIT_FAILURE );}delete [] s.source;glAttachShader( program, shader ); } /* link and error check */ glLinkProgram(program); GLint linked; glGetProgramiv( program, GL_LINK_STATUS, &linked ); if ( !linked ) {std::cerr << "Shader program failed to link" << std::endl;GLint logSize;glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);char* logMsg = new char[logSize];glGetProgramInfoLog( program, logSize, NULL, logMsg );std::cerr << logMsg << std::endl;delete [] logMsg;exit( EXIT_FAILURE ); } /* use program object */ glUseProgram(program); return program;}} // Close namespace Angel block
0 0
- OpenGL立方体在世界坐标系中_缩放_旋转_平移_顶点片源着色器_光照作用
- OpenGL立方体在世界坐标系中_缩放_旋转_平移_顶点片源着色器_光照作用_棋盘纹理贴图
- OpenGL立方体在世界坐标系中_缩放_旋转_平移_顶点片源着色器
- OpenGL ES _ 着色器_顶点着色器和片断着色器详解
- ^_^
- ^_^
- ^_^
- ^_^
- *_&
- ...!@~....!@#....+_#%.
- ^_^
- ^_^
- ^_^
- ^_^
- *_*
- ^_^
- ^_^
- ~~~~(>_<)~~~~
- 编写的windows程序,崩溃时产生crash dump文件的办法
- 直接改应用!Flipboard开源iOS应用内调试工具FLEX
- 写在开篇
- 常用虚拟化工具概述
- hibernate实现单个对象的增删改查,以及实现分页查询
- OpenGL立方体在世界坐标系中_缩放_旋转_平移_顶点片源着色器_光照作用
- 杭电4546
- 购物商城shopping连载(8)
- 【Data Algorithms_Recipes for Scaling up with Hadoop and Spark】Chapter 11 Smarter Email Marketing wit
- HDU1671Phone List
- 记毕设中遇到的菜鸡问题----2
- UIKit层面的动画
- 【JavaScript】基础知识整理(三)
- Testing with Xcode文档(中文版)