參考文章: 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);
}