一、 绘制
在窗口中间画一个像素点:
cpp
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
using namespace std;
#define numVAOs 1
GLuint renderingProgram;
GLuint vao[numVAOs];
GLuint
createShaderProgram ()
{
const char *vshaderSource = "#version 460 \n"
"void main(void) \n"
"{ gl_Position = vec4(0.0, 0.0, 0.0, 1.0); }";
const char *fshaderSource = "#version 460 \n"
"out vec4 color; \n"
"void main(void) \n"
"{ color = vec4(0.0, 0.0, 1.0, 1.0); }";
GLuint vShader = glCreateShader (GL_VERTEX_SHADER);
GLuint fShader = glCreateShader (GL_FRAGMENT_SHADER);
glShaderSource (vShader, 1, &vshaderSource, NULL);
glShaderSource (fShader, 1, &fshaderSource, NULL);
glCompileShader (vShader);
glCompileShader (fShader);
GLuint vfProgram = glCreateProgram();
glAttachShader (vfProgram, vShader);
glAttachShader (vfProgram, fShader);
glLinkProgram (vfProgram);
return vfProgram;
}
void
display (GLFWwindow *window, double currTime)
{
glUseProgram (renderingProgram);
glDrawArrays (GL_POINTS, 0, 1);
}
void
init (GLFWwindow *window)
{
renderingProgram = createShaderProgram();
glGenVertexArrays (numVAOs, vao);
glBindVertexArray (vao[0]);
}
int
main (int argc, char *argv[])
{
if (!glfwInit()) {
return -1;
}
glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 6);
GLFWwindow *window = glfwCreateWindow (600, 600, "Chapter2 - program1", nullptr, nullptr);
glfwMakeContextCurrent (window);
int errorCode = glewInit();
if (errorCode != GLEW_OK) {
cerr << "Error: " << glewGetErrorString (errorCode) << endl;
return -1;
}
glfwSwapInterval (1);
init (window);
while (!glfwWindowShouldClose (window)) {
display (window, glfwGetTime());
glfwSwapBuffers (window);
glfwPollEvents();
}
glfwDestroyWindow (window);
glfwTerminate();
return 0;
}
点太小了很难看见,可以把它调大点:
cpp
void
display(GLFWindow *window, double currTime)
{
glUseProgram(renderingProgram);
glPointSize(30);
glDrawArrays(GL_POINTS, 0, 1);
}
现在,栅格化阶段从顶点着色器收到顶点时,会设置像素的颜色,组成一个尺寸为30像素的点。
二、预定义变量说明
1. gl_Position
内置变量gl_Position
用来设置顶点在3D空间中的坐标位置,并将其发送到下一个管线阶段。
GLSL数据类型vec4用来存储四元组,适合用来存储坐标,四元组的前3个值分别表示x、y、z坐标,第4个值在这里设为1.0(暂时不用了解)。
本例中,顶点坐标被硬编码为原点。
2. gl_FragCord
还可以用预定义变量gl_FragCord
来控制颜色,
修改着色器代码:
cpp
fshaderSource = R"(
#version 460
out vec4 color;
void main(void)
{
if(gl_FragCoord.x < 295)
color = vec4(1.0, 0.0, 0.0, 1.0);
else
color = vec4(0.0, 0.0, 1.0, 1.0);
}
)";