feat: initialize OpenGL

This commit is contained in:
2026-03-05 17:01:01 +08:00
parent 83c271ec8f
commit 9fe1eaec24
21 changed files with 5866 additions and 0 deletions

131
src/camera.cpp Normal file
View File

@@ -0,0 +1,131 @@
#include "Cubed/camera.hpp"
static glm::vec3 cameraPos;
static float speed = 0.1f;
static float lastMouseX, lastMouseY;
static bool firseMouse = true;
static MoveState moveState;
static float yaw, pitch;
static glm::vec3 front = glm::vec3(0, 0, -1);
static float sensitivity = 0.05f;
static glm::vec3 rightPos;
void updateMoveCamera() {
rightPos = glm::normalize(glm::cross(front, glm::vec3(0.0f, 1.0f, 0.0f)));
if (moveState.forward) {
cameraPos += glm::vec3(front.x, 0.0f, front.z) * speed;
}
if (moveState.back) {
cameraPos -= glm::vec3(front.x, 0.0f, front.z) * speed;
}
if (moveState.left) {
cameraPos -= glm::vec3(rightPos.x, 0.0f, rightPos.z) * speed;
}
if (moveState.right) {
cameraPos += glm::vec3(rightPos.x, 0.0f, rightPos.z) * speed;
}
if (moveState.up) {
cameraPos += glm::vec3(0.0f, 1.0f, 0.0f) * speed;;
}
if (moveState.down) {
cameraPos -= glm::vec3(0.0f, 1.0f, 0.0f) * speed;;
}
}
void cameraInit() {
cameraPos = glm::vec3(0.0f, 0.0f, 5.0f);
}
void changeView(float offsetX, float offsetY) {
yaw += offsetX * sensitivity;
pitch += offsetY * sensitivity;
if (pitch > 89.0f) pitch = 89.0f;
if (pitch < -89.0f) pitch = -89.0f;
front.x = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
front.y = sin(glm::radians(pitch));
front.z = -cos(glm::radians(yaw)) * cos(glm::radians(pitch));
front = glm::normalize(front);
}
void updateCursorPositionCamera(double xpos, double ypos) {
if (firseMouse) {
lastMouseX = xpos;
lastMouseY = ypos;
firseMouse = false;
}
float offsetX = xpos - lastMouseX;
float offsetY = lastMouseY - ypos;
lastMouseX = xpos;
lastMouseY = ypos;
changeView(offsetX, offsetY);
}
glm::mat4 getCameraLookAt() {
return glm::lookAt(cameraPos, cameraPos + front, glm::vec3(0.0f, 1.0f, 0.0f));
}
void updateCameraKey(int key, int action) {
switch(key) {
case GLFW_KEY_W:
if (action == GLFW_PRESS) {
moveState.forward = true;
}
if (action == GLFW_RELEASE) {
moveState.forward = false;
}
break;
case GLFW_KEY_S:
if (action == GLFW_PRESS) {
moveState.back = true;
}
if (action == GLFW_RELEASE) {
moveState.back = false;
}
break;
case GLFW_KEY_A:
if (action == GLFW_PRESS) {
moveState.left = true;
}
if (action == GLFW_RELEASE) {
moveState.left = false;
}
break;
case GLFW_KEY_D:
if (action == GLFW_PRESS) {
moveState.right = true;
}
if (action == GLFW_RELEASE) {
moveState.right = false;
}
break;
case GLFW_KEY_SPACE:
if (action == GLFW_PRESS) {
moveState.up = true;
}
if (action == GLFW_RELEASE) {
moveState.up = false;
}
break;
case GLFW_KEY_LEFT_SHIFT:
if (action == GLFW_PRESS) {
moveState.down = true;
}
if (action == GLFW_RELEASE) {
moveState.down = false;
}
break;
}
}

305
src/main.cpp Normal file
View File

@@ -0,0 +1,305 @@
#include <fstream>
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <Cubed/camera.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/shader_tools.hpp>
constexpr int numVAOs = 1;
constexpr int numVBOs = 3;
GLuint renderingProgram;
GLuint vao[numVAOs];
GLuint vbo[numVBOs];
GLuint pyrTexture;
float cubLocX, cubLocY, cubLocZ;
float pyLocX, pyLocY, pyLocZ;
GLuint mvLoc, projLoc, tfLoc;
int width ,height;
float aspect;
glm::mat4 pMat, vMat, mMat, mvMat;
float inc = 0.01f;
float tf = 0.0f;
glm::mat4 tMat, rMat, sMat;
void setupVertices(void) {
float verticesPos[108] = {
// ===== 后面 (z = -1) =====
-1.0f, -1.0f, -1.0f, // 左下
1.0f, -1.0f, -1.0f, // 右下
1.0f, 1.0f, -1.0f, // 右上
1.0f, 1.0f, -1.0f, // 右上
-1.0f, 1.0f, -1.0f, // 左上
-1.0f, -1.0f, -1.0f, // 左下
// ===== 前面 (z = +1) =====
-1.0f, -1.0f, 1.0f, // 左下
-1.0f, 1.0f, 1.0f, // 左上
1.0f, 1.0f, 1.0f, // 右上
1.0f, 1.0f, 1.0f, // 右上
1.0f, -1.0f, 1.0f, // 右下
-1.0f, -1.0f, 1.0f, // 左下
// ===== 左面 (x = -1) =====
-1.0f, -1.0f, -1.0f, // 后下
-1.0f, -1.0f, 1.0f, // 前下
-1.0f, 1.0f, 1.0f, // 前上
-1.0f, 1.0f, 1.0f, // 前上
-1.0f, 1.0f, -1.0f, // 后上
-1.0f, -1.0f, -1.0f, // 后下
// ===== 右面 (x = +1) =====
1.0f, -1.0f, 1.0f, // 前下
1.0f, -1.0f, -1.0f, // 后下
1.0f, 1.0f, -1.0f, // 后上
1.0f, 1.0f, -1.0f, // 后上
1.0f, 1.0f, 1.0f, // 前上
1.0f, -1.0f, 1.0f, // 前下
// ===== 上面 (y = +1) =====
-1.0f, 1.0f, -1.0f, // 后左
1.0f, 1.0f, -1.0f, // 后右
1.0f, 1.0f, 1.0f, // 前右
1.0f, 1.0f, 1.0f, // 前右
-1.0f, 1.0f, 1.0f, // 前左
-1.0f, 1.0f, -1.0f, // 后左
// ===== 下面 (y = -1) =====
-1.0f, -1.0f, 1.0f, // 前左
1.0f, -1.0f, 1.0f, // 前右
1.0f, -1.0f, -1.0f, // 后右
1.0f, -1.0f, -1.0f, // 后右
-1.0f, -1.0f, -1.0f, // 后左
-1.0f, -1.0f, 1.0f // 前左
};
float tex_coords[72] {
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f,
};
glGenVertexArrays(numVAOs, vao);
glBindVertexArray(vao[0]);
glGenBuffers(numVBOs, vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(verticesPos), verticesPos, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(tex_coords), tex_coords, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
GLuint createShaderProgram() {
std::string vShaderStr = readShaderSource("shaders/vShader.glsl");
std::string fShaderStr = readShaderSource("shaders/fShader.glsl");
const char *vshaderSource = vShaderStr.c_str();
const char *fshaderSource = fShaderStr.c_str();
GLuint vShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fShader = glCreateShader(GL_FRAGMENT_SHADER);
GLint vc, fc;
glShaderSource(vShader, 1, &vshaderSource, NULL);
glShaderSource(fShader, 1, &fshaderSource, NULL);
glCompileShader(vShader);
checkOpenGLError();
glGetShaderiv(vShader, GL_COMPILE_STATUS, &vc);
if (vc != 1) {
LOG::error("vertex compilation failed");
printShaderLog(vShader);
}
glCompileShader(fShader);
checkOpenGLError();
glGetShaderiv(fShader, GL_COMPILE_STATUS, &fc);
if (fc != 1) {
LOG::error("vertex compilation failed");
printShaderLog(fShader);
}
GLuint vfProgram = glCreateProgram();
glAttachShader(vfProgram, vShader);
glAttachShader(vfProgram, fShader);
glLinkProgram(vfProgram);
GLint linked;
checkOpenGLError();
glGetProgramiv(vfProgram, GL_LINK_STATUS, &linked);
if (linked != 1) {
LOG::error("linking failed");
printProgramInfo(vfProgram);
}
return vfProgram;
}
void init(GLFWwindow* window) {
renderingProgram = createShaderProgram();
cubLocX = 0.0f;
cubLocY = -2.0f;
cubLocZ = 0.0f;
pyLocX = 0.0f;
pyLocY = -2.0f;
pyLocZ = -20.0f;
cameraInit();
glfwGetFramebufferSize(window, &width, &height);
aspect = (float)width / (float)height;
glViewport(0, 0, width, height);
pMat = glm::perspective(glm::radians(60.0f), aspect, 0.1f, 1000.0f);
pyrTexture = loadTexture("assets/texture/block/grass_block/top.png");
setupVertices();
}
void window_reshape_callback(GLFWwindow* window, int newWidth, int newHeight) {
glfwGetFramebufferSize(window, &width, &height);
aspect = (float)width / (float)height;
glViewport(0, 0, width, height);
pMat = glm::perspective(glm::radians(60.0f), aspect, 0.1f, 1000.0f);
}
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos) {
updateCursorPositionCamera(xpos, ypos);
}
void display(GLFWwindow* window, double currentTime) {
updateMoveCamera();
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_DEPTH_BUFFER_BIT);
glUseProgram(renderingProgram);
mvLoc = glGetUniformLocation(renderingProgram, "mv_matrix");
projLoc = glGetUniformLocation(renderingProgram, "proj_matrix");
/*
cameraX += inc;
if (cameraX > 1.0f) {
inc = -inc;
}
if (cameraX < -1.0f) {
inc = -inc;
}
*/
glBindVertexArray(vao[0]);
//sMat = glm::scale(glm::mat4(1.0f), glm::vec3(0.3f, 0.3f, 0.3f));
mMat = glm::translate(glm::mat4(1.0f), glm::vec3(pyLocX, pyLocY, pyLocZ));
vMat = getCameraLookAt();
mvMat = vMat * mMat;
glUniformMatrix4fv(mvLoc, 1, GL_FALSE, glm::value_ptr(mvMat));
glUniformMatrix4fv(projLoc, 1 ,GL_FALSE, glm::value_ptr(pMat));
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, pyrTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glGenerateMipmap(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
//glPointSize(30.0f);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
switch(key) {
case GLFW_KEY_ESCAPE:
if (action == GLFW_PRESS) {
if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
} else if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_NORMAL) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
}
break;
}
updateCameraKey(key, action);
}
int main() {
if (!glfwInit()) {
LOG::error("glfwinit fail");
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
GLFWwindow* window = glfwCreateWindow(800, 600, "Cubed", NULL, NULL);
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
LOG::error("Failed to initialize glad");
return -1;
}
LOG::info("OpenGL Version: {}.{}", GLVersion.major, GLVersion.minor);
LOG::info("Renderer: {}", reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
glfwSwapInterval(1);
glfwSetWindowSizeCallback(window, window_reshape_callback);
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
init(window);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
while(!glfwWindowShouldClose(window)) {
display(window, glfwGetTime());
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}

12
src/shaders/fShader.glsl Normal file
View File

@@ -0,0 +1,12 @@
#version 430
in vec2 tc;
in vec4 varyingColor;
out vec4 color;
layout (binding = 0) uniform sampler2D samp;
void main(void) {
color = texture(samp, tc);
//color = varyingColor;
}

63
src/shaders/vShader.glsl Normal file
View File

@@ -0,0 +1,63 @@
#version 430
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texCoord;
out vec2 tc;
mat4 buildRotateX(float rad);
mat4 buildRotateY(float rad);
mat4 buildRotateZ(float rad);
mat4 buildTranslate(float x, float y, float z);
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
out vec4 varyingColor;
layout (binding = 0) uniform sampler2D samp;
void main(void) {
gl_Position = proj_matrix * mv_matrix * vec4(pos, 1.0);
tc = texCoord;
varyingColor = vec4(pos, 1.0) * 0.5 + vec4(0.5, 0.5, 0.5, 0.5);
}
mat4 buildTranslate(float x, float y, float z) {
mat4 trans = mat4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
x, y, z, 1.0
);
return trans;
}
mat4 buildRotateX(float rad) {
mat4 xrot = mat4(
1.0, 0.0, 0.0, 0.0,
0.0, cos(rad), -sin(rad), 0.0,
0.0, sin(rad), cos(rad), 0.0,
0.0, 0.0, 0.0, 1.0
);
return xrot;
}
mat4 buildRotateY(float rad) {
mat4 yrot = mat4(
cos(rad), 0.0, sin(rad), 0.0,
0.0, 1.0, 0.0, 0.0,
-sin(rad), 0.0, cos(rad), 0.0,
0.0, 0.0, 0.0, 1.0
);
return yrot;
}
mat4 buildRotateZ(float rad) {
mat4 zrot = mat4(
cos(rad), -sin(rad), 0.0, 0.0,
sin(rad), cos(rad), 0.0, 0.0,
0.0, 0.0,1.0 , 0.0,
0.0, 0.0, 0.0, 1.0
);
return zrot;
}

6
src/tools/log.cpp Normal file
View File

@@ -0,0 +1,6 @@
#include <Cubed/tools/log.hpp>
namespace LOG {
}

View File

@@ -0,0 +1,72 @@
#include <Cubed/tools/shader_tools.hpp>
#include <Cubed/tools/log.hpp>
void printShaderLog(GLuint shader) {
int len = 0;
int chWritten = 0;
char *log;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetShaderInfoLog(shader, len, &chWritten, log);
LOG::info("Shader Info Log: {}", log);
free(log);
}
}
void printProgramInfo(int prog) {
int len = 0;
int chWritten = 0;
char *log;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetProgramInfoLog(prog, len, &chWritten, log);
LOG::info("Program Info Log: {}", log);
free(log);
}
}
bool checkOpenGLError() {
bool foundError = false;
int glErr = glGetError();
while (glErr != GL_NO_ERROR) {
LOG::error("glEorr: {}", glErr);
foundError = true;
glErr = glGetError();
}
return foundError;
}
std::string readShaderSource(const char* filePath) {
std::string content;
std::ifstream fileStream(filePath, std::ios::in);
if (!fileStream.is_open()) {
LOG::error("file not exist");
}
std::string line = "";
while (!fileStream.eof()) {
getline(fileStream, line);
content.append(line + "\n");
}
fileStream.close();
return content;
}
GLuint loadTexture(const char* texImagePath) {
GLuint textureID;
textureID = SOIL_load_OGL_texture(texImagePath, SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y);
if (textureID == 0) {
LOG::error("could not find texture file");
}
return textureID;
}