OpenGL-05-02练习题

OpenGL-05-02练习题

一、使用应用在箱子上的最后一个变换,尝试将其改变为先旋转,后位移。看看发生了什么,试着想想为什么会发生这样的事情

glm::mat4 trans;
trans = glm::rotate(trans, (float)glfwGetTime(), glm::vec3(0.0, 0.0, 1.0));
trans = glm::translate(trans, glm::vec3(1, 0, 0));
ourShader.setMatrix("transform",trans);

这里我把对于uniform mat4的传递操作封装到了着色器类里,正常写应该是这样

unsigned int transformLoc = glGetUniformLocation(ourShader.ID, "transform");
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans));

这样做,会出现箱子绕着中心旋转的效果,因为是先位移在旋转。如果是先旋转在位移的话,那就是在位移之后的位置原地旋转了,注意变化的叠加顺序,这非常重要

二、尝试再次调用glDrawElements画出第二个箱子,使用变换将其摆放在不同的位置。让这个箱子被摆放在窗口的左上角,并且会不断的缩放(而不是旋转)。(sin函数在这里会很有用,不过注意使用sin函数时应用负值会导致物体被翻转)

渲染指令

        ourShader.use();
        glm::mat4 trans;
        float timeValue=sin(glfwGetTime())/2+0.5f;
        trans = glm::translate(trans, glm::vec3(0.6, 0, 0));
        trans = glm::scale(trans,glm::vec3(timeValue,timeValue,timeValue));
        ourShader.setMatrix("transform",trans);

        scale=virtualInput(window,scale);
        ourShader.setFloat("mixScale",scale);

        glBindVertexArray(VAO);
        //真正渲染
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT,0);
//
        trans=glm::mat4(1.0f);
        trans = glm::translate(trans, glm::vec3(-0.6, 0.6, 0));
        trans = glm::scale(trans,glm::vec3(timeValue,timeValue,timeValue));
        ourShader.setMatrix("transform",trans);

        glBindVertexArray(VAO);
        //真正渲染
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT,0);

完整代码

//顶点
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;

out vec3 ourColor;
out vec2 TexCoord;

uniform mat4 transform;

void main()
{
   gl_Position = transform*vec4(aPos, 1.0);
   ourColor = aColor;
   TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}
//片段
#version 330 core
out vec4 FragColor;

in vec3 ourColor;
in vec2 TexCoord;

// texture sampler
uniform sampler2D texture1;
uniform sampler2D texture2;
uniform float mixScale;

void main()
{
	 FragColor = mix(texture(texture1, TexCoord), texture(texture2, TexCoord), mixScale);
}
#pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <myShader.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>

#include <iostream>

void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
float virtualInput(GLFWwindow *window,float value);

// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;

int main()
{

#pragma region glfw
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }
#pragma endregion

    // build and compile our shader zprogram
    // ------------------------------------
    Shader ourShader("path/to/shaders/shader.vs", "path/to/shaders/shader.fs");

    // set up vertex data (and buffer(s)) and configure vertex attributes
    // ------------------------------------------------------------------
    float vertices[] = {
            // positions                        // colors                       // texture1 coords
            0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f, // top right
            0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f, // bottom right
            -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f, // bottom left
            -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f  // top left
    };
    unsigned int indices[] = {
            0, 1, 3, // first triangle
            1, 2, 3  // second triangle
    };
    unsigned int VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    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);

    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    // color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);
    // texture1 coord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);


    // load and create a texture1
    // -------------------------
    //创建纹理ID
    unsigned int texture1;
    //生成纹理对象,并存储在texture中
    glGenTextures(1, &texture1);
    //绑定当前的纹理
    glBindTexture(GL_TEXTURE_2D,texture1); // all upcoming GL_TEXTURE_2D operations now have effect on this texture1 object
    // 为当前绑定的纹理对象设置环绕、过滤方式
    // set the texture1 wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);	// set texture1 wrapping to GL_REPEAT (default wrapping method)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    // 为当前绑定的纹理对象设置环绕、过滤方式
    // set texture1 filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture1 and generate mipmaps
    int width, height, nrChannels;
    // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
    unsigned char *data = stbi_load("Texture/container.jpeg", &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 texture1" << std::endl;
    }
    //释放图像内存
    stbi_image_free(data);

    stbi_set_flip_vertically_on_load(true);
    // load and create a texture1
    // -------------------------
    //创建纹理ID
    unsigned int texture2;
    //生成纹理对象,并存储在texture中
    glGenTextures(1, &texture2);
    //绑定当前的纹理
    glBindTexture(GL_TEXTURE_2D,texture2); // all upcoming GL_TEXTURE_2D operations now have effect on this texture1 object
    // 为当前绑定的纹理对象设置环绕、过滤方式
    // set the texture1 wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);	// set texture1 wrapping to GL_REPEAT (default wrapping method)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
    // 为当前绑定的纹理对象设置环绕、过滤方式
    // set texture1 filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // load image, create texture1 and generate mipmaps
    // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
    data = stbi_load("Texture/awesomeface.png", &width, &height, &nrChannels, 0);
    if (data)
    {
        //生成纹理.注意awesomeface.png有透明度和alpha通道,所以一定要告诉OpenGL的数据类型是GL_RGBA
        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 texture1" << std::endl;
    }
    //释放图像内存
    stbi_image_free(data);

    // tell opengl for each sampler to which texture1 unit it belongs to (only has to be done once)
    // -------------------------------------------------------------------------------------------
    ourShader.use(); // don't forget to activate/use the shader before setting uniforms!
    // either set it manually like so:
    ourShader.setInt("texture1",0);
    // or set it via the texture1 class
    ourShader.setInt("texture2", 1);
    ourShader.setFloat("mixScale",1);


    float scale=1.0f;
    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // input
        // -----
        processInput(window);

        // render
        // ------
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        stbi_set_flip_vertically_on_load(true);
        // bind Texture
        // bind textures on corresponding texture1 units
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D,texture1);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D,texture2);

        // render container
        ourShader.use();
        glm::mat4 trans;
        float timeValue=sin(glfwGetTime())/2+0.5f;
        trans = glm::translate(trans, glm::vec3(0.6, 0, 0));
        trans = glm::scale(trans,glm::vec3(timeValue,timeValue,timeValue));
        ourShader.setMatrix("transform",trans);

        scale=virtualInput(window,scale);
        ourShader.setFloat("mixScale",scale);

        glBindVertexArray(VAO);
        //真正渲染
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT,0);
//
        trans=glm::mat4(1.0f);
        trans = glm::translate(trans, glm::vec3(-0.6, 0.6, 0));
        trans = glm::scale(trans,glm::vec3(timeValue,timeValue,timeValue));
        ourShader.setMatrix("transform",trans);

        glBindVertexArray(VAO);
        //真正渲染
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT,0);

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // optional: de-allocate all resources once they've outlived their purpose:
    // ------------------------------------------------------------------------
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}


float virtualInput(GLFWwindow *window,float value){
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){
        value=value+0.1f;
        if(value>1) value=1;
    }else if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){
        value=value-0.1f;
        if(value<0) value=0;
    }
    return value;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
}

// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值