opengl根据代码编译顶点着色器和片段着色器,但是程序最终呈现的貌似只是默认的着色器,自己编译的没成功,但是程序却不报错,有人知道是为什么么
#include<glad\glad.h>
#include<GLFW\glfw3.h>
#include<stdio.h>
float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
//*着色器源码存入字符串
const char * vertexShaderSource = "#version 400 core\n "
"layout(location=0) in vec3 aPos;\n"//将VBO中的数据取出来给aPos
"void mian()\n"
"{\n"
"gl_Position = vec4(aPos.x+0.5, aPos.y, aPos.z, 1.0f);\n"
"}\n\0";
const char * fragmentShaderSource = "#version 400 core\n "
"out vec4 FragColor;\n"
"void mian()\n"
"{\n"
"FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
GLFWwindow* window;
void init();
void VAOSet();
void init(){
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);//版本号
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//核心模式
window = glfwCreateWindow(800, 600, "OPENGL", NULL, NULL);//指针指向窗口
if (window == NULL)
{
printf("err:windows is NULL");
glfwTerminate();
return;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
printf("err:gladLoadGLLoader is NULL");
return;
}
}
void VAOSet(){//VAO只是管理,真正的数据是分配在VBO的
unsigned int VBO, VAO;//ID号
glGenVertexArrays(1, &VAO);//数组
glGenBuffers(1, &VBO);//生成内存空间
//绑定与opengl上下文进行绑定
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER,VBO);
//往显卡写值,分配内存空间,值不改变GL_STATIC_DRAW
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
//告诉显卡,值的结构
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);//0开始,xyz,类型,是否需要标准化,大小,偏移
glEnableVertexAttribArray(0);//启用它,此处的0与上一行的0一致
}
int main(){//生成窗口
init();
VAOSet();
//2*渲染引擎前创建着色器对象
int vertexShader = glCreateShader(GL_VERTEX_SHADER);//告诉类型,会产生一个ID,来指代着色器对象
//3*将源码绑定对象
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);//着色器对象,一个,源码地址
//4*编译
glCompileShader(vertexShader);
//2*渲染引擎前创建着色器对象
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);//告诉类型,会产生一个ID,来指代着色器对象
//3*将源码绑定对象
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);//着色器对象,一个,源码地址
//4*编译
glCompileShader(fragmentShader);
//5*创建着色器程序对象
int shaderProgram = glCreateProgram();//程序ID
//6*将着色器附加到着色器程序上
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
//7*链接生成程序,编译
glLinkProgram(shaderProgram);
//渲染引擎
while (!glfwWindowShouldClose(window)){
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);//告诉编译器我现在要使用自己创建的着色器程序,而不是默认的
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwPollEvents();
glfwSwapBuffers(window);
}
//退出
glfwTerminate();
return 0;
}