VERTEX_SHADER
#version 150 core in vec2 position; in vec3 color; out vec3 Color; void main(){ Color=color; gl_Position=vec4(position.x,-position.y,0,1); }
FRAGMENT_SHADER
#version 150 core out vec4 outColor; in vec3 Color; uniform vec3 triangleColor; void main(){ //outColor=vec4(triangleColor,1.0); outColor=vec4(Color,1.0); }
源文件:#include"glew.h"
#include<Windows.h> #include"freeglut.h" #include<gl\GL.h> #include<random> #include"LoadShaders.h" //使用红宝书8版工具 GLuint vao; GLuint vbo; GLuint ebo; GLuint uniColor; GLfloat rColor=1.f; void Init(){ GLfloat vertices[] = { 0.0,0.5, 1.f,0.f,0.f, 0.5,-0.5, 0.f,1.f,0.f, -0.5,-0.5, 0.f,0.f,1.f }; GLuint elements[] = { 0, 1, 2 }; ShaderInfo shaders[] = { {GL_VERTEX_SHADER,"vertexShader.txt"}, {GL_FRAGMENT_SHADER,"fragementShader.txt"}, {GL_NONE,NULL} }; GLuint shaderProgram = LoadShaders(shaders); //**VAO开始记录 glGenVertexArrays(1, &vao); glBindVertexArray(vao); //*VBO glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //*EBO glGenBuffers(1, &ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); //*数据配接 glUseProgram(shaderProgram); GLuint posAttri = glGetAttribLocation(shaderProgram, "position"); glVertexAttribPointer(posAttri, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GL_FLOAT), 0); glEnableVertexAttribArray(posAttri); GLuint colorAttri = glGetAttribLocation(shaderProgram, "color"); glVertexAttribPointer(colorAttri, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GL_FLOAT), (void*)(2 * sizeof(GL_FLOAT))); glEnableVertexAttribArray(colorAttri); uniColor = glGetUniformLocation(shaderProgram, "triangleColor"); glUniform3f(uniColor, 1.f, 0.f, 0.f); glClearColor(0, 0, 0, 1); } void Display(){ glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUniform3f(uniColor, rColor, 0.f, 0.f); //glDrawArrays(GL_TRIANGLES, 0, 3); glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0); glFlush(); } //作者使用定时改变颜色,这里利用键盘、随机数改变颜色 void KeyboardFunc(unsigned char key,int x,int y){ static std::default_random_engine dre; static std::uniform_int_distribution<int> di(1, 100); switch (key) { case ‘c‘: rColor = std::abs(std::sin((double)di(dre))); glutPostRedisplay(); break; default: break; } } int main(int argc,char** argv){ glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGBA); glutInitWindowSize(512, 512); glutInitWindowPosition(100, 200); glutInitContextVersion(3, 2); glutInitContextProfile(GLUT_CORE_PROFILE); glutCreateWindow(argv[0]); glewExperimental = true; glewInit(); Init(); glutDisplayFunc(Display); glutKeyboardFunc(KeyboardFunc); glutMainLoop(); return 0; }
时间: 2024-10-29 19:08:20