第四個OpenGL程式,vector 向量 (矩陣變換之 旋轉,縮放)後續 繪製多個 圖形

雾枫發表於2024-04-07
效果:

程式碼 main.cpp

#include <iostream>
#include <glad/glad.h>
#include <glfw3.h>
#include "Shader.h"
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <chrono>
#include <thread>
using namespace std;

// 回撥函式,每當視窗改變大小,視口大小也跟隨改變
void framebuffer_size_callback(GLFWwindow* window,int width,int height)
{
    glViewport(0,0,width,height);
}

// 輸入 在GLFW中實現一些輸入控制
void processInput(GLFWwindow *window)
{
    if(glfwGetKey(window,GLFW_KEY_ESCAPE) == GLFW_PRESS)     // 是否按下了返回鍵(Esc)
    {
        glfwSetWindowShouldClose(window,true);               // 把WindowShouldClose屬性設定為 true來關閉GLFW
    }
}
// ************** opengl 具體實現 ************
    // 頂點資料
float vertices[] = {
    //     ---- 位置 ----    - 紋理座標 -
     0.5f,  0.5f,  0.0f,     1.0f, 1.0f,   // 右上
     0.5f, -0.5f,  0.0f,     1.0f, 0.0f,   // 右下
    -0.5f,  -0.5f, 0.0f,     0.0f, 0.0f,   // 左下
    -0.5f,   0.5f, 0.0f,     0.0f, 1.0f    // 左上
};

    // 紋理索引
unsigned int indices[] = {
    // 注意索引從0開始!
    // 此例的索引(0,1,2,3)就是頂點陣列vertices的下標,
    // 這樣可以由下標代表頂點組合成矩形

    0, 1, 3, // 第一個三角形
    1, 2, 3  // 第二個三角形
};
//******************************************
int main()
{
    cout << "紋理" << endl;


// GLFW (視窗)
    glfwInit();                                                         // 初始化GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);                       // 主版本號
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);                       // 次版本號
    glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);       // 使用核心模式
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); Mac OS X系統

    // 建立一個GLFW視窗物件
    GLFWwindow* window = glfwCreateWindow(800,600,"texture",NULL,NULL);
    if(window == NULL)
    {
        std::cout<< "Failed to create GLFW window"<<std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);                              // 視窗的上下文設定為當前執行緒的主上下文

// GLAD
    if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))      // 初始化GLAD(初始化OpenGL函式指標)
    {
        std::cout<<"Failed to initialize GLAD"<<std::endl;
        return -1;
    }

//*********** opengl 具體實現 ******************
    // 著色器類
    Shader shader("E:\\Project\\openglstudy2\\05_OpenglVector\\05_OpenglVector\\vertexSourceCode.vert",
                  "E:\\Project\\openglstudy2\\05_OpenglVector\\05_OpenglVector\\fragmentSourceCode.frag");

    // 頂點陣列物件 VAO
    unsigned int VAO;
    glGenVertexArrays(1,&VAO);   // 建立頂點陣列物件
    glBindVertexArray(VAO);      // 繫結頂點陣列物件
    // 頂點緩衝物件 VBO
    unsigned int VBO;
    glGenBuffers(1,&VBO);
    glBindBuffer(GL_ARRAY_BUFFER,VBO);                                       // 繫結頂點緩衝物件
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);  // 把之前定義的頂點資料複製到緩衝的記憶體中
    // 索引快取物件 EBO
    unsigned int EBO;
    glGenBuffers(1,&EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,EBO);                                       // 繫結索引緩衝物件
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW);  // 把之前定義的索引資料複製到索引緩衝的記憶體中

    // 連結頂點屬性 (告訴 gpu 如何解析記憶體中的頂點資料)
    // 0 位置座標
    glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,5 * sizeof(float),(void*)0);
    glEnableVertexAttribArray(0);
    // 1 紋理座標
    glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,5 * sizeof(float),(void*)(3*sizeof(float)));
    glEnableVertexAttribArray(1);

    unsigned int texture1,texture2;
    // 紋理物件1 texture1
    glGenTextures(1,&texture1);
    glBindTexture(GL_TEXTURE_2D,texture1);

    // 設定紋理影像環繞方式
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // 設定紋理過濾
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // 載入圖片
    int width,height,nrChannels;
    unsigned char *data = stbi_load("E:\\Project\\openglstudy2\\resources\\textures\\container.jpg",
                                    &width,&height,&nrChannels,0);
    if(data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    // 釋放掉影像資料
    stbi_image_free(data);

    shader.use();
    // 紋理物件2 texture2
    glGenTextures(1,&texture2);
    glBindTexture(GL_TEXTURE_2D,texture2);

    // 設定紋理影像環繞方式
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);    // 重複
    // 設定紋理過濾
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // 載入圖片
    stbi_set_flip_vertically_on_load(true);
    data = stbi_load("E:\\Project\\openglstudy2\\resources\\textures\\awesomeface.png",
                                    &width,&height,&nrChannels,0);
    if(data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
    }
    // 釋放掉影像資料
    stbi_image_free(data);

    // 設定取樣器對應的紋理單元(unform)
    shader.use();
    shader.setInt("texture1",0);
    shader.setInt("texture2",1);

    // 變換
    float scal = 0.1;
    bool flag = true;
    unsigned int transformLoc = glGetUniformLocation(shader.ID,"transform");
//**************************




// 視口
    glViewport(0,0,800,600);

// 視口跟隨視窗大小改變
    glfwSetFramebufferSizeCallback(window,framebuffer_size_callback);

// 渲染迴圈
    while(!glfwWindowShouldClose(window))                            // 檢查GLFW是否被要求退出
    {
        // 輸入 (使用者)
        processInput(window);                                        // 輸入控制(自定義)

        //************** 渲染指令 (使用者)**********

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture2);

        glBindVertexArray(VAO);

        // create transformations
        glm::mat4 transform; // make sure to initialize matrix to identity matrix first
        transform = glm::translate(transform, glm::vec3(0.5f, 0.5f, 0.0f));
        auto gltime =  (float)glfwGetTime();
        transform = glm::rotate(transform, gltime*2, glm::vec3(0.0f, 0.0f, 1.0f));
        transform = glm::scale(transform, glm::vec3(scal, scal, scal));
        if(scal >= 1.0)  // 自己實現的縮放效果
        {
            flag = false;
        }
        else if(scal <= 0.1)
        {
            flag = true;
        }

        if(flag)
        {
            scal +=0.1;
        }
        else
        {
            scal -= 0.1;
        }

        // get matrix's uniform location and set matrix
        shader.use();
        unsigned int transformLoc = glGetUniformLocation(shader.ID, "transform");
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform));
        glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);


        // create transformations
        glm::mat4 transform2; // make sure to initialize matrix to identity matrix first
        transform2 = glm::translate(transform2, glm::vec3(0.5f, -0.5f, 0.0f));
        transform2 = glm::rotate(transform2, (float)glfwGetTime()*4, glm::vec3(0.0f, 0.0f, 1.0f));
        float scaleAmount = static_cast<float>(sin(glfwGetTime()));
        transform2 = glm::scale(transform2, glm::vec3(scaleAmount, scaleAmount, scaleAmount));
        // get matrix's uniform location and set matrix
        shader.use();
        unsigned int transformLoc2 = glGetUniformLocation(shader.ID, "transform");
        glUniformMatrix4fv(transformLoc2, 1, GL_FALSE, glm::value_ptr(transform2));
        glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);


        // create transformations
        glm::mat4 transform3; // make sure to initialize matrix to identity matrix first
        transform3 = glm::translate(transform3, glm::vec3(-0.5f, 0.5f, 0.0f));
        transform3 = glm::rotate(transform3, (float)glfwGetTime()*6, glm::vec3(0.0f, 0.0f, 1.0f));
        transform3 = glm::scale(transform3, glm::vec3(scaleAmount, scaleAmount, scaleAmount));
        // get matrix's uniform location and set matrix
        shader.use();
        unsigned int transformLoc3 = glGetUniformLocation(shader.ID, "transform");
        glUniformMatrix4fv(transformLoc3, 1, GL_FALSE, glm::value_ptr(transform3));
        glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);

        // create transformations
        glm::mat4 transform4; // make sure to initialize matrix to identity matrix first
        transform4 = glm::translate(transform4, glm::vec3(-0.5f, -0.5f, 0.0f));
        transform4 = glm::rotate(transform4, (float)glfwGetTime()*8, glm::vec3(0.0f, 0.0f, 1.0f));
        transform4 = glm::scale(transform4, glm::vec3(scaleAmount, scaleAmount, scaleAmount));
        // get matrix's uniform location and set matrix
        shader.use();
        unsigned int transformLoc4 = glGetUniformLocation(shader.ID, "transform");
        glUniformMatrix4fv(transformLoc4, 1, GL_FALSE, glm::value_ptr(transform4));
        glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);



        //***************************************

        // 檢查並呼叫事件,交換緩衝 (預設操作)
        glfwSwapBuffers(window);                                     // 交換顏色緩衝(它是一個儲存著GLFW視窗每一個畫素顏色值的大緩衝),它在這一迭代中被用來繪製,並且將會作為輸出顯示在螢幕上。
        glfwPollEvents();                                            // 有沒有觸發什麼事件(比如鍵盤輸入、滑鼠移動等)、更新視窗狀態
    }

    // 解綁 VAO  VBO 著色器程式物件
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);


// 當渲染迴圈結束後我們需要正確釋放/刪除之前的分配的所有資源
    glfwTerminate();
    return 0;
}

著色器程式碼:

頂點著色器:

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;

out vec2 TexCoord;

uniform mat4 transform;
void main()
{
   gl_Position = transform * vec4(aPos,1.0) ;
   TexCoord = vec2(aTexCoord.x, 1-aTexCoord.y);
}

片段著色器:

#version 330 core
out vec4 FragColor;

in vec3 ourColor;
in vec2 TexCoord;

// 定義一個全域性的2D紋理取樣器
uniform sampler2D texture1;
uniform sampler2D texture2;
void main()
{
    // GLSL內建的mix函式需要接受兩個值作為引數,並對它們根據第三個引數進行線性插值。
  FragColor = mix(texture(texture1, TexCoord), texture(texture2, vec2(-TexCoord.x,TexCoord.y)), 0.2);
}

相關文章