参考文章: https://learnopengl-cn.readthedocs.io/zh/latest/
现有问题:
问题1: GLSL现阶段貌似只有float类型,貌似4.0有更高的精度,这会导致放大一些后就出现模糊的情况。
问题2: 按键我暂时没管了,需要连续按,如果不喜欢可以用标志位解决。但是我发现貌似glfw的鼠标键盘事件貌似都不怎么灵敏,不知道是不是使用方式有误。
最终代码:
- main.cpp
#include <iostream>
#include <ctime>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "Shader.h"
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
// Window dimensions
const GLuint WIDTH = 1000, HEIGHT = 1000;
GLfloat vertices[WIDTH * HEIGHT][3];
GLfloat alphax, alphay;
GLfloat rateZoom = 1.5f;
GLfloat cx = -1, cy = -1;
bool stop = false;
void func(float rate) {
if (stop) return;
static bool flag = true;
if (flag) cx += rate;
else cx -= rate;
if (cx > 1) {
cy += rate;
flag = false;
}
if (cx < -1) {
cy += rate;
flag = true;
}
if (cy == 0) {
cx += rate;
}
}
double CalFrequency() {
static int count;
static double save;
static clock_t last, current;
double timegap;
++count;
if (count <= 50)
return save;
count = 0;
last = current;
current = clock();
timegap = (current - last) / (double)CLK_TCK;
save = 50.0 / timegap;
return save;
}
int main() {
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
glewInit();
// Define the viewport dimensions
glViewport(0, 0, WIDTH, HEIGHT);
// vertices
// x0,y0,z0
// ...
for (int i = 0; i < WIDTH; i++)
for (int j = 0; j < HEIGHT; j++) {
vertices[i * HEIGHT + j][0] = (float)i / WIDTH * 2 - 1;
vertices[i * HEIGHT + j][1] = (float)j / HEIGHT * 2 - 1;
vertices[i * HEIGHT + j][2] = 0;
}
// Build and compile our shader program
Shader ourShader("default.vs", "default.frag");
GLuint VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0); // Unbind VAO
// Game loop
while (!glfwWindowShouldClose(window)) {
double FPS = CalFrequency();
printf("FPS = %f\n", FPS);
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
GLint alphaLoc = glGetUniformLocation(ourShader.Program, "alpha");
GLint rateZoomLoc = glGetUniformLocation(ourShader.Program, "rateZoom");
GLint cLoc = glGetUniformLocation(ourShader.Program, "C");
glUniform2f(alphaLoc, alphax, alphay);
glUniform1f(rateZoomLoc, rateZoom);
glUniform2f(cLoc, cx, cy);
// Draw the triangle
ourShader.Use();
glBindVertexArray(VAO);
glDrawArrays(GL_POINTS, 0, WIDTH * HEIGHT);
glBindVertexArray(0);
// Swap the screen buffers
glfwSwapBuffers(window);
// 这么高的FPS,只能调小步长了
func(0.01);
}
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
double addRate = 0.1 * std::abs(std::exp(rateZoom) - 1);
if (action == GLFW_PRESS) {
switch (key)
{
case GLFW_KEY_UP:
alphay += addRate;
break;
case GLFW_KEY_DOWN:
alphay -= addRate;
break;
case GLFW_KEY_LEFT:
alphax -= addRate;
break;
case GLFW_KEY_RIGHT:
alphax += addRate;
break;
case GLFW_KEY_PAGE_UP:
rateZoom -= addRate;
break;
case GLFW_KEY_PAGE_DOWN:
rateZoom = (rateZoom + addRate) > 2 ? 2 : rateZoom + addRate;
break;
case GLFW_KEY_SPACE:
stop = !stop;
break;
default:
break;
}
}
}
- Shader.h
#ifndef SHADER_H
#define SHADER_H
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <GL/glew.h>
class Shader {
public:
GLuint Program;
// Constructor generates the shader on the fly
Shader(const GLchar* vertexPath, const GLchar* fragmentPath) {
// 1. Retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
// ensures ifstream objects can throw exceptions:
vShaderFile.exceptions(std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::badbit);
try {
// Open files
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
// Read file's buffer contents into streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// close file handlers
vShaderFile.close();
fShaderFile.close();
// Convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure e) {
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
}
const GLchar* vShaderCode = vertexCode.c_str();
const GLchar* fShaderCode = fragmentCode.c_str();
// 2. Compile shaders
GLuint vertex, fragment;
GLint success;
GLchar infoLog[512];
// Vertex Shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
// Print compile errors if any
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vertex, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Fragment Shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
// Print compile errors if any
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fragment, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// Shader Program
this->Program = glCreateProgram();
glAttachShader(this->Program, vertex);
glAttachShader(this->Program, fragment);
glLinkProgram(this->Program);
// Print linking errors if any
glGetProgramiv(this->Program, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(this->Program, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
// Delete the shaders as they're linked into our program now and no longer necessery
glDeleteShader(vertex);
glDeleteShader(fragment);
}
// Uses the current shader
void Use() {
glUseProgram(this->Program);
}
};
#endif
- default.vs
#version 330 core
layout (location = 0) in vec3 position;
out vec3 ourColor;
uniform float rateZoom;
uniform vec2 alpha;
uniform vec2 C; // (-0.8,0.156)
void main()
{
const int N = 100;
const float M = 1000;
vec2 X = vec2(position.x*rateZoom, position.y*rateZoom);
X += alpha;
vec3 color;
for(int k=0;k<N;k++){
// X = X*X; X = X+C;
X = vec2(X.x*X.x - X.y*X.y , 2*X.x*X.y);
X += C;
if(X.x*X.x+X.y*X.y > M){
// 配色1
float gi = float(k) / 100.0;
color.x = gi;
color.y = (1.0-X.x) * gi;
color.z = (1.0-X.y) * gi;
// 配色2
/*int tempK = k * k;
tempK = tempK * tempK;
int x = tempK + tempK;
int y = int(exp(k)); // 必须加上int()强制类型转化,GLSL没有隐式转换,左右类型必须一致;
int z = tempK * tempK;
color.x = float(x%255)/255.0;
color.y = float(y%255)/255.0;
color.z = float(z%255)/255.0;*/
break;
}
}
ourColor = color;
gl_Position = vec4(position, 1.0f);
}
- default.frag
#version 330 core
in vec3 ourColor;
out vec4 color;
void main()
{
color = vec4(ourColor, 1.0f);
}
等待更新一些代码的解释。
更新:
经过评论提醒,确实可以只传递6个顶点(两个三角形绘制),然后让GPU插值。这样不用每次渲染传入WIDTH*HEIGHT*3
的数组了。
但是我开始一直把处理写到了Vertex Shader,一直不行就一张渐变图,后来才想到渲染管线的过程,Vertex Shader只有刚传入的顶点,还没有光栅化!
Fragment Shader是在光栅化之后。在Vertex Shader阶段,我们要处理的数据只是3个顶点,而在Fragment Shader阶段,我们要处理的则是(大致上)被这三个顶点围住的所有像素对应的Fragments。Vertex的数量远远少于Fragment。
现在帧率又一次爆炸了,大概1000-1500(配色1)、500-1200帧(配色2)左右了(我已经麻木了 ○| ̄|_)
- main.cpp
#include <iostream>
#include <ctime>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "Shader.h"
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
// Window dimensions
const GLuint WIDTH = 1000, HEIGHT = 1000;
GLfloat alphax, alphay;
GLfloat rateZoom = 1.5f;
GLfloat cx = -1, cy = -1;
bool stop = false;
void func(float rate) {
if (stop) return;
static bool flag = true;
if (flag) cx += rate;
else cx -= rate;
if (cx > 1) {
cy += rate;
flag = false;
}
if (cx < -1) {
cy += rate;
flag = true;
}
if (cy == 0) {
cx += rate;
}
}
double CalFrequency() {
static int count;
static double save;
static clock_t last, current;
double timegap;
++count;
if (count <= 50)
return save;
count = 0;
last = current;
current = clock();
timegap = (current - last) / (double)CLK_TCK;
save = 50.0 / timegap;
return save;
}
int main() {
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
glewInit();
// Define the viewport dimensions
glViewport(0, 0, WIDTH, HEIGHT);
GLfloat vertices[] = {
1, 1, 0.0f, // Top Right
1, -1, 0.0f, // Bottom Right
-1, -1, 0.0f, // Bottom Left
-1, 1, 0.0f // Top Left
};
GLuint indices[] = { // Note that we start from 0!
0, 1, 3, // First Triangle
1, 2, 3 // Second Triangle
};
// Build and compile our shader program
Shader ourShader("default.vs", "default.frag");
GLuint VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO
// Game loop
while (!glfwWindowShouldClose(window)) {
double FPS = CalFrequency();
printf("FPS = %f\n", FPS);
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
GLint alphaLoc = glGetUniformLocation(ourShader.Program, "alpha");
GLint rateZoomLoc = glGetUniformLocation(ourShader.Program, "rateZoom");
GLint cLoc = glGetUniformLocation(ourShader.Program, "C");
glUniform2f(alphaLoc, alphax, alphay);
glUniform1f(rateZoomLoc, rateZoom);
glUniform2f(cLoc, cx, cy);
// Draw the triangle
ourShader.Use();
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// Swap the screen buffers
glfwSwapBuffers(window);
// 这么高的FPS,只能调小步长了
func(0.01);
}
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
double addRate = 0.1 * std::abs(std::exp(rateZoom) - 1);
if (action == GLFW_PRESS) {
switch (key)
{
case GLFW_KEY_UP:
alphay += addRate;
break;
case GLFW_KEY_DOWN:
alphay -= addRate;
break;
case GLFW_KEY_LEFT:
alphax -= addRate;
break;
case GLFW_KEY_RIGHT:
alphax += addRate;
break;
case GLFW_KEY_PAGE_UP:
rateZoom -= addRate;
break;
case GLFW_KEY_PAGE_DOWN:
rateZoom = (rateZoom + addRate) > 2 ? 2 : rateZoom + addRate;
break;
case GLFW_KEY_SPACE:
stop = !stop;
break;
default:
break;
}
}
}
-
Shader.h文件未变
-
default.vs
#version 330 core
layout (location = 0) in vec3 position;
out vec3 color;
void main()
{
color = position;
gl_Position = vec4(position, 1.0f);
}
- default.frag
#version 330 core
in vec3 color;
out vec4 colorF;
uniform float rateZoom;
uniform vec2 alpha;
uniform vec2 C; // (-0.8,0.156)
void main()
{
const int N = 100;
const float M = 1000;
vec2 X = vec2(color.x*rateZoom, color.y*rateZoom);
X += alpha;
vec3 color;
for(int k=0;k<N;k++){
// X = X*X; X = X+C;
X = vec2(X.x*X.x - X.y*X.y , 2*X.x*X.y);
X += C;
if(X.x*X.x+X.y*X.y > M){
// 配色1
float gi = float(k) / 100.0;
color.x = gi;
color.y = (1.0-X.x) * gi;
color.z = (1.0-X.y) * gi;
// 配色2
/*int tempK = k * k;
tempK = tempK * tempK;
int x = tempK + tempK;
int y = int(exp(k)); // 必须加上int()强制类型转化,GLSL没有隐式转换,左右类型必须一致;
int z = tempK * tempK;
color.x = float(x%255)/255.0;
color.y = float(y%255)/255.0;
color.z = float(z%255)/255.0;*/
break;
}
}
colorF = vec4(color, 1.0f);
}