OpenGL学习——19.模板测试

前情提要:本文代码源自Github上的学习文档“LearnOpenGL”,我仅在源码的基础上加上中文注释。本文章不以该学习文档做任何商业盈利活动,一切著作权归原作者所有,本文仅供学习交流,如有侵权,请联系我删除。LearnOpenGL原网址:https://learnopengl.com/ 请大家多多支持原作者!


当涉及到实现复杂的图形效果和场景交互时,OpenGL(Open Graphics Library)是开发人员的首选工具之一。其中一个强大的功能是模板测试(Stencil Testing),它允许我们根据模板缓冲区中的值来控制像素的绘制和渲染。模板测试是一种基于像素的测试机制,可以在绘制过程中根据模板缓冲区的特定位进行条件判断,从而决定是否绘制像素。这为开发人员提供了更强大的控制能力,可以实现各种有趣的效果,如遮罩、镂空、镜像反射等。
在本篇博客文章中,我们将深入探讨OpenGL中的模板测试机制。我们将了解如何使用glStencilFunc函数来设置模板测试的函数和参考值,以及如何使用glStencilMask来控制模板缓冲区中各个位的写入。我们还将讨论不同的模板测试函数和它们的应用场景,以及如何结合模板缓冲区与其他OpenGL功能来实现更复杂的效果。
通过深入理解模板测试的原理和使用方法,您将能够更加灵活地控制像素的绘制和渲染,为您的OpenGL应用程序增添更多的视觉魅力和交互性。让我们一起开始探索OpenGL的模板测试功能吧!

项目结构:

模型压缩包下载链接:

https://learnopengl-cn.github.io/data/nanosuit.rar

(请用鼠标右键点击,在新标签页打开链接)

下载到资源文件夹内模型文件夹内解压即可,保存路径是\resources\models\nanosuit

container2.png图片:

(请右键图片另存为到你的项目文件夹中)

container2_specular.png图片:

(请右键图片另存为到你的项目文件夹中)

下载到资源文件夹内的图片文件夹内即可,保存路径是\resources\images\

vs_multiple_lights.txt着色器代码:
#version 330 core
 
layout (location = 0) in vec3 aPos;   // 位置变量的属性位置值为 0 
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;
 
out vec3 FragPos;  
out vec3 Normal;
out vec2 TexCoords;
out mat4 View;
 
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
 
void main()
{
    gl_Position = projection * view * model * vec4(aPos, 1.0);
 
    FragPos = vec3(model * vec4(aPos, 1.0));
    Normal = mat3(transpose(inverse(model))) * aNormal;
    TexCoords = aTexCoords;
    View = view;
}
fs_multiple_lights.txt着色器代码:
#version 330 core
 
// 材质
struct Material {
    sampler2D diffuse;
    sampler2D specular;    
    float shininess;
}; 
 
// 定向光
struct DirLight {
    vec3 direction;
 
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};  
uniform DirLight dirLight;
 
// 点光源
struct PointLight {
    vec3 position;
 
    float constant;
    float linear;
    float quadratic;
 
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};  
#define NR_POINT_LIGHTS 4
uniform PointLight pointLights[NR_POINT_LIGHTS];
 
// 聚光
struct SpotLight {
    sampler2D spotlightMap;
    float cutOff;
    float outerCutOff;
 
    vec3 position;
    vec3 direction;
 
    float constant;
    float linear;
    float quadratic;
 
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};
uniform SpotLight spotLight;
 
out vec4 FragColor; // 输出片段颜色
 
in vec3 FragPos;  
in vec3 Normal;
in vec2 TexCoords;
in mat4 View;
 
uniform vec3 viewPos;
uniform Material material;
 
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir);
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir);
vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir);
 
void main()
{
    // 属性
    vec3 norm = normalize(Normal);
    vec3 viewDir = normalize(viewPos - FragPos);
 
    // 第一阶段:定向光照
    vec3 result = CalcDirLight(dirLight, norm, viewDir);
    // 第二阶段:点光源
    for(int i = 0; i < NR_POINT_LIGHTS; i++)
        result += CalcPointLight(pointLights[i], norm, FragPos, viewDir);    
    // 第三阶段:聚光
    result += CalcSpotLight(spotLight, norm, FragPos, viewDir);    
 
    FragColor = vec4(result, 1.0);
    // FragColor = vec4(vec3(gl_FragCoord.z), 1.0);
}
 
// 计算定向光(Calculate Direction Light)
vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir)
{
    vec3 lightDir = normalize(-light.direction);
    // 漫反射着色
    float diff = max(dot(normal, lightDir), 0.0);
    // 镜面光着色
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    // 合并结果
    vec3 ambient  = light.ambient  * vec3(texture(material.diffuse, TexCoords));
    vec3 diffuse  = light.diffuse  * diff * vec3(texture(material.diffuse, TexCoords));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
    return (ambient + diffuse + specular);
}
 
// 计算点光源(Calculate Point Light)
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{
    vec3 lightDir = normalize(light.position - fragPos);
    // 漫反射着色
    float diff = max(dot(normal, lightDir), 0.0);
    // 镜面光着色
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    // 衰减
    float distance    = length(light.position - fragPos);
    float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));    
    // 合并结果
    vec3 ambient  = light.ambient  * vec3(texture(material.diffuse, TexCoords));
    vec3 diffuse  = light.diffuse  * diff * vec3(texture(material.diffuse, TexCoords));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
    ambient  *= attenuation;
    diffuse  *= attenuation;
    specular *= attenuation;
    return (ambient + diffuse + specular);
}
 
// 计算聚光(Calculate Spot Light)
vec3 CalcSpotLight(SpotLight light, vec3 normal, vec3 fragPos, vec3 viewDir)
{
    // 切光角
    vec3 lightDir = normalize(light.position - fragPos);
    float theta = dot(lightDir, normalize(-light.direction));
    float epsilon  = light.cutOff - light.outerCutOff;
    float intensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0); 
    
    // 执行光照计算
    if(theta > light.outerCutOff) 
    {       
        vec3 lightDir = normalize(light.position - fragPos);
 
        // 漫反射着色
        float diff = max(dot(normal, lightDir), 0.0);
 
        // 镜面光着色
        vec3 reflectDir = reflect(-lightDir, normal);
        float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
 
        // 图案
        vec4 view = View * vec4(fragPos, 1.0);
        vec2 texcoord = normalize(view.xyz).xy;
 
        // 衰减
        float distance = length(light.position - fragPos);
        float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
  
        // 合并结果
        vec3 ambient  = light.ambient  * vec3(texture(material.diffuse, TexCoords));
        vec3 diffuse = light.diffuse  * diff * vec3(texture(material.diffuse, TexCoords));
        vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));
        vec3 spotdiffuse = diff * vec3(texture(light.spotlightMap, ((texcoord) / 0.7 + 0.5)));
 
        ambient  *= attenuation;
        diffuse  *= attenuation * intensity;
        specular *= attenuation * intensity;
        spotdiffuse *= attenuation * intensity;
 
        return (ambient + diffuse + specular);
    }
}
vs_light_cube.txt着色器代码:
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoords;

out vec2 TexCoords;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    TexCoords = aTexCoords;    
    gl_Position = projection * view * model * vec4(aPos, 1.0f);
}
fs_light_cube.txt着色器代码:
#version 330 core
out vec4 FragColor; // 输出片段颜色

uniform vec3 lightCubeColor;

void main()
{
    FragColor = vec4(lightCubeColor, 1.0);
}
vs_single_color.txt着色器代码:
#version 330 core
layout (location = 0) in vec3 aPos;   // 位置变量的属性位置值为 0 
layout (location = 1) in vec3 aNormal;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

out vec3 Normal;
out vec3 FragPos;

void main()
{
    Normal = mat3(transpose(inverse(model))) * aNormal;
    gl_Position = projection * view * model * (vec4(aPos, 1.0) + vec4(0.05 * Normal, 0));
    FragPos = vec3(model * vec4(aPos, 1.0)) + 0.05 * aNormal;
}
fs_single_color.txt着色器代码:
#version 330 core
out vec4 FragColor;

void main()
{
    FragColor = vec4(0.0, 0.3, 0.7, 1.0);
}
SHADER_H.h头文件代码:
#ifndef SHADER_H

#define SHADER_H

#include <glad/glad.h>;
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>



/* 着色器类 */
class Shader
{
public:
    /* 着色器程序 */
    unsigned int shaderProgram;

    /* 构造函数,从文件读取并构建着色器 */
    Shader(const char* vertexPath, const char* fragmentPath)
    {
        std::string vertexCode;
        std::string fragmentCode;
        std::ifstream vShaderFile;
        std::ifstream fShaderFile;
        /* 保证ifstream对象可以抛出异常: */
        vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
        fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
        try
        {
            /* 打开文件 */
            vShaderFile.open(vertexPath);
            fShaderFile.open(fragmentPath);
            std::stringstream vShaderStream, fShaderStream;
            /* 读取文件的缓冲内容到数据流中 */
            vShaderStream << vShaderFile.rdbuf();
            fShaderStream << fShaderFile.rdbuf();
            /* 关闭文件处理器 */
            vShaderFile.close();
            fShaderFile.close();
            /* 转换数据流到string */
            vertexCode = vShaderStream.str();
            fragmentCode = fShaderStream.str();
        }
        catch (std::ifstream::failure e)
        {
            std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
        }

        /* string类型转化为char字符串类型 */
        const char* vShaderCode = vertexCode.c_str();
        const char* fShaderCode = fragmentCode.c_str();

        /* 着色器 */
        unsigned int vertex, fragment;
        int success;
        /* 信息日志(编译或运行报错信息) */
        char infoLog[512];

        /* 顶点着色器 */
        vertex = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertex, 1, &vShaderCode, NULL);
        /* 编译 */
        glCompileShader(vertex);
        /* 打印编译错误(如果有的话) */
        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 = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragment, 1, &fShaderCode, NULL);
        /* 编译 */
        glCompileShader(fragment);
        /* 打印编译错误(如果有的话) */
        glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
        if (!success)
        {
            glGetShaderInfoLog(fragment, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
        }

        /* 着色器程序 */
        shaderProgram = glCreateProgram();
        /* 连接顶点着色器和片段着色器到着色器程序中 */
        glAttachShader(shaderProgram, vertex);
        glAttachShader(shaderProgram, fragment);
        /* 链接着色器程序到我们的程序中 */
        glLinkProgram(shaderProgram);
        /* 打印连接错误(如果有的话) */
        glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
        if (!success)
        {
            glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
        }

        /* 删除着色器,它们已经链接到我们的程序中了,已经不再需要了 */
        glDeleteShader(vertex);
        glDeleteShader(fragment);
    }

    /* 激活着色器程序 */
    void use()
    {
        glUseProgram(shaderProgram);
    }

    /* 实用程序统一函数,Uniform工具函数,用于设置uniform类型的数值 */
    // ------------------------------------------------------------------------
    void setBool(const std::string& name, bool value) const
    {
        glUniform1i(glGetUniformLocation(shaderProgram, name.c_str()), (int)value);
    }
    // ------------------------------------------------------------------------
    void setInt(const std::string& name, int value) const
    {
        glUniform1i(glGetUniformLocation(shaderProgram, name.c_str()), value);
    }
    // ------------------------------------------------------------------------
    void setFloat(const std::string& name, float value) const
    {
        glUniform1f(glGetUniformLocation(shaderProgram, name.c_str()), value);
    }
    // ------------------------------------------------------------------------
    void setVec2(const std::string& name, const glm::vec2& value) const
    {
        glUniform2fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, &value[0]);
    }
    void setVec2(const std::string& name, float x, float y) const
    {
        glUniform2f(glGetUniformLocation(shaderProgram, name.c_str()), x, y);
    }
    // ------------------------------------------------------------------------
    void setVec3(const std::string& name, const glm::vec3& value) const
    {
        glUniform3fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, &value[0]);
    }
    void setVec3(const std::string& name, float x, float y, float z) const
    {
        glUniform3f(glGetUniformLocation(shaderProgram, name.c_str()), x, y, z);
    }
    // ------------------------------------------------------------------------
    void setVec4(const std::string& name, const glm::vec4& value) const
    {
        glUniform4fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, &value[0]);
    }
    void setVec4(const std::string& name, float x, float y, float z, float w) const
    {
        glUniform4f(glGetUniformLocation(shaderProgram, name.c_str()), x, y, z, w);
    }
    // ------------------------------------------------------------------------
    void setMat2(const std::string& name, const glm::mat2& mat) const
    {
        glUniformMatrix2fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
    }
    // ------------------------------------------------------------------------
    void setMat3(const std::string& name, const glm::mat3& mat) const
    {
        glUniformMatrix3fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
    }
    // ------------------------------------------------------------------------
    void setMat4(const std::string& name, const glm::mat4& mat) const
    {
        glUniformMatrix4fv(glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
    }

    /* 删除着色器程序 */
    void deleteProgram()
    {
        glDeleteProgram(shaderProgram);
    }
};



#endif
camera.h头文件代码:
#ifndef CAMERA_H

#define CAMERA_H

#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include <vector>

/* 定义摄影机移动的几个可能选项。 */
enum Camera_Movement {
    /* 前进 */
    FORWARD,
    /* 后退 */
    BACKWARD,
    /* 左移 */
    LEFT,
    /* 右移 */
    RIGHT,
    /* 上升 */
    RISE,
    /* 下降 */
    FALL
};

/* 默认摄像机参数 */
/* 偏航角 */
const float YAW = -90.0f;
/* 俯仰角 */
const float PITCH = 0.0f;
/* 速度 */
const float SPEED = 2.5f;
/* 鼠标灵敏度 */
const float SENSITIVITY = 0.1f;
/* 视野 */
const float ZOOM = 70.0f;


/* 一个抽象的摄影机类,用于处理输入并计算相应的欧拉角、向量和矩阵,以便在OpenGL中使用 */
class Camera
{
public:
    /* 摄影机属性 */
    /* 位置 */
    glm::vec3 Position;
    /* 朝向 */
    glm::vec3 Front;
    /* 上轴 */
    glm::vec3 Up;
    /* 右轴 */
    glm::vec3 Right;
    /* 世界竖直向上方向 */
    glm::vec3 WorldUp;

    /* 偏航角 */
    float Yaw;
    /* 俯仰角 */
    float Pitch;

    /* 摄影机选项 */
    /* 移动速度 */
    float MovementSpeed;
    /* 鼠标灵敏度 */
    float MouseSensitivity;
    /* 视野 */
    float Zoom;

    /* 矢量的构造函数 */
    Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
    {
        Position = position;
        WorldUp = up;
        Yaw = yaw;
        Pitch = pitch;
        updateCameraVectors();
    }
    /* 标量的构造函数 */
    Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVITY), Zoom(ZOOM)
    {
        Position = glm::vec3(posX, posY, posZ);
        WorldUp = glm::vec3(upX, upY, upZ);
        Yaw = yaw;
        Pitch = pitch;
        updateCameraVectors();
    }

    /* 返回使用欧拉角和LookAt矩阵计算的视图矩阵 */
    glm::mat4 GetViewMatrix()
    {
        return glm::lookAt(Position, Position + Front, Up);
    }

    /* 处理从任何类似键盘的输入系统接收的输入。接受相机定义ENUM形式的输入参数(从窗口系统中提取) */
    void ProcessKeyboard(Camera_Movement direction, float deltaTime)
    {
        float velocity = MovementSpeed * deltaTime;
        if (direction == FORWARD)
            Position += Front * velocity;
        if (direction == BACKWARD)
            Position -= Front * velocity;
        if (direction == LEFT)
            Position -= Right * velocity;
        if (direction == RIGHT)
            Position += Right * velocity;
        if (direction == RISE)
            Position += WorldUp * velocity;
        if (direction == FALL)
            Position -= WorldUp * velocity;
    }

    /* 处理从鼠标输入系统接收的输入。需要x和y方向上的偏移值。 */
    void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true)
    {
        xoffset *= MouseSensitivity;
        yoffset *= MouseSensitivity;

        Yaw += xoffset;
        Pitch += yoffset;

        /* 确保当俯仰角超出范围时,屏幕不会翻转 */
        if (constrainPitch)
        {
            if (Pitch > 89.0f)
                Pitch = 89.0f;
            if (Pitch < -89.0f)
                Pitch = -89.0f;
        }

        /* 使用更新的欧拉角更新“朝向”、“右轴”和“上轴” */
        updateCameraVectors();
    }

    /* 处理从鼠标滚轮事件接收的输入 */
    void ProcessMouseScroll(float yoffset)
    {
        Zoom -= (float)yoffset;
        if (Zoom < 10.0f)
            Zoom = 10.0f;
        if (Zoom > 120.0f)
            Zoom = 120.0f;
    }

private:
    /* 根据摄影机的(更新的)欧拉角计算摄影机朝向 */
    void updateCameraVectors()
    {
        /* 计算新的摄影机朝向 */
        glm::vec3 front;
        front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
        front.y = sin(glm::radians(Pitch));
        front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));
        Front = glm::normalize(front);
        /* 还重新计算右轴和上轴 */
        /* 重新规范(修正)向量,因为当它们的长度越接近0或向上向下看得多时,将会导致移动速度变慢 */
        Right = glm::normalize(glm::cross(Front, WorldUp));
        Up = glm::normalize(glm::cross(Right, Front));
    }
};



#endif
MESH_H.h头文件代码:
#ifndef MESH_H
#define MESH_H

// 包含所有OpenGL类型声明
#include <glad/glad.h> 

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include "SHADER_H.h"

#include <string>
#include <vector>
using namespace std;

#define MAX_BONE_INFLUENCE 4

struct Vertex {
    // 位置
    glm::vec3 Position;
    // 法线
    glm::vec3 Normal;
    // 纹理坐标
    glm::vec2 TexCoords;
    // 切线
    glm::vec3 Tangent;
    // 双切线
    glm::vec3 Bitangent;
    // 影响此顶点的骨骼索引
    int m_BoneIDs[MAX_BONE_INFLUENCE];
    // 每块骨骼的权重
    float m_Weights[MAX_BONE_INFLUENCE];
};

struct Texture {
    unsigned int id;
    string type;
    string path;
};

class Mesh {
public:
    // 网格数据
    vector<Vertex>       vertices;
    vector<unsigned int> indices;
    vector<Texture>      textures;
    unsigned int VAO;

    // 建造者
    Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<Texture> textures)
    {
        this->vertices = vertices;
        this->indices = indices;
        this->textures = textures;

        // 现在我们已经拥有了所有必需的数据,设置顶点缓冲区及其属性指针。
        setupMesh();
    }

    // 渲染网格
    void Draw(Shader& shader)
    {
        // 绑定适当的纹理
        unsigned int diffuseNr = 1;
        unsigned int specularNr = 1;
        unsigned int normalNr = 1;
        unsigned int heightNr = 1;
        for (unsigned int i = 0; i < textures.size(); i++)
        {
            // 绑定前激活正确的纹理单元
            glActiveTexture(GL_TEXTURE0 + i); 
            // 检索纹理编号(diffuse_textureN中的N)
            string number;
            string name = textures[i].type;
            if (name == "texture_diffuse")
                number = std::to_string(diffuseNr++);
            else if (name == "texture_specular")
                number = std::to_string(specularNr++); // 将无符号int转换为字符串
            else if (name == "texture_normal")
                number = std::to_string(normalNr++); // 将无符号int转换为字符串
            else if (name == "texture_height")
                number = std::to_string(heightNr++); // 将无符号int转换为字符串

            // 现在将采样器设置为正确的纹理单位
            glUniform1i(glGetUniformLocation(shader.shaderProgram, (name + number).c_str()), i);
            // 并最终绑定纹理
            glBindTexture(GL_TEXTURE_2D, textures[i].id);
        }

        // 绘制网格
        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, static_cast<unsigned int>(indices.size()), GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // 一旦配置好,将所有内容都设置回默认值始终是一种好做法。
        glActiveTexture(GL_TEXTURE0);
    }

private:
    // 渲染数据
    unsigned int VBO, EBO;

    // 初始化所有缓冲区对象/数组
    void setupMesh()
    {
        // 创建缓冲区/阵列
        glGenVertexArrays(1, &VAO);
        glGenBuffers(1, &VBO);
        glGenBuffers(1, &EBO);

        glBindVertexArray(VAO);
        // 将数据加载到顶点缓冲区
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        // structs的一个优点是,它们的内存布局对所有项目都是顺序的。
        // 其效果是,我们可以简单地将指针传递到结构,它可以完美地转换为glm::vec3/2数组,
        // 该数组再次转换为3/2浮点,该浮点转换为字节数组。
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

        // 设置顶点属性指针
        // 顶点位置
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
        // 顶点法线
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
        // 顶点纹理坐标
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
        // 顶点切线
        glEnableVertexAttribArray(3);
        glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
        // 顶点双切
        glEnableVertexAttribArray(4);
        glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));
        // 索引
        glEnableVertexAttribArray(5);
        glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)offsetof(Vertex, m_BoneIDs));
        // 权重
        glEnableVertexAttribArray(6);
        glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_Weights));
        glBindVertexArray(0);
    }
};
#endif
MODEL_H.h头文件代码:
#ifndef MODEL_H
#define MODEL_H

#include <glad/glad.h> 

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "stb_image.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

#include "MESH_H.h"
#include "SHADER_H.h"

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;

unsigned int TextureFromFile(const char* path, const string& directory, bool gamma = false);

class Model
{
public:
    // 模型数据
    vector<Texture> textures_loaded;	// 存储到目前为止加载的所有纹理,进行优化以确保纹理不会被重复加载。
    vector<Mesh>    meshes;
    string directory;
    bool gammaCorrection;

    // 构造函数,接受一个指向 3D 模型的文件路径作为参数。
    Model(string const& path, bool gamma = false) : gammaCorrection(gamma)
    {
        loadModel(path);
    }

    // 绘制该模型以及其所有网格。
    void Draw(Shader& shader)
    {
        for (unsigned int i = 0; i < meshes.size(); i++)
            meshes[i].Draw(shader);
    }

private:
    // 从文件加载具有支持的 ASSIMP 扩展名的模型,并将生成的网格存储在网格向量中。
    void loadModel(string const& path)
    {
        // 通过 ASSIMP 读取文件。
        Assimp::Importer importer;
        const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
        // 检查是否有错误。
        if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
        {
            cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
            return;
        }
        // 获取文件路径的目录路径。
        directory = path.substr(0, path.find_last_of('/'));

        // process ASSIMP's root node recursively
        processNode(scene->mRootNode, scene);
    }

    // 以递归方式处理节点。处理位于节点上的每个独立网格,并对其子节点(如果有)重复此过程。
    void processNode(aiNode* node, const aiScene* scene)
    {
        // 处理当前节点上的每个网格。
        for (unsigned int i = 0; i < node->mNumMeshes; i++)
        {
            // 节点对象只包含用于索引场景中实际对象的索引。
            // 场景包含所有数据,节点仅用于组织数据(例如节点之间的关系)。
            aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
            meshes.push_back(processMesh(mesh, scene));
        }
        // 在处理完所有网格(如果有的话)后,我们递归处理每个子节点。
        for (unsigned int i = 0; i < node->mNumChildren; i++)
        {
            processNode(node->mChildren[i], scene);
        }

    }

    Mesh processMesh(aiMesh* mesh, const aiScene* scene)
    {
        // 要填充的数据。
        vector<Vertex> vertices;
        vector<unsigned int> indices;
        vector<Texture> textures;

        // 遍历每个网格的顶点。
        for (unsigned int i = 0; i < mesh->mNumVertices; i++)
        {
            Vertex vertex;
            glm::vec3 vector; // 我们声明一个占位符向量,因为Assimp使用其自己的向量类,无法直接转换为glm的vec3类,所以我们首先将数据转移到这个占位符glm::vec3中。
            // 位置
            vector.x = mesh->mVertices[i].x;
            vector.y = mesh->mVertices[i].y;
            vector.z = mesh->mVertices[i].z;
            vertex.Position = vector;
            // 法线
            if (mesh->HasNormals())
            {
                vector.x = mesh->mNormals[i].x;
                vector.y = mesh->mNormals[i].y;
                vector.z = mesh->mNormals[i].z;
                vertex.Normal = vector;
            }
            // 纹理坐标。
            if (mesh->mTextureCoords[0]) // 该网格是否包含纹理坐标?
            {
                glm::vec2 vec;
                // 一个顶点最多可以包含8个不同的纹理坐标。因此,我们假设我们不会使用顶点可以具有多个纹理坐标的模型,因此我们始终使用第一个集合(0)。
                vec.x = mesh->mTextureCoords[0][i].x;
                vec.y = mesh->mTextureCoords[0][i].y;
                vertex.TexCoords = vec;
                // 切线
                vector.x = mesh->mTangents[i].x;
                vector.y = mesh->mTangents[i].y;
                vector.z = mesh->mTangents[i].z;
                vertex.Tangent = vector;
                // 双切线
                vector.x = mesh->mBitangents[i].x;
                vector.y = mesh->mBitangents[i].y;
                vector.z = mesh->mBitangents[i].z;
                vertex.Bitangent = vector;
            }
            else
                vertex.TexCoords = glm::vec2(0.0f, 0.0f);

            vertices.push_back(vertex);
        }
        // 现在遍历每个网格的面(一个面是网格的三角形),并获取相应的顶点索引。
        for (unsigned int i = 0; i < mesh->mNumFaces; i++)
        {
            aiFace face = mesh->mFaces[i];
            // 获取面的所有索引,并将它们存储在索引向量中。
            for (unsigned int j = 0; j < face.mNumIndices; j++)
                indices.push_back(face.mIndices[j]);
        }
        // 处理材质。
        aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
        // 我们假设着色器中采样器名称的约定。每个漫反射纹理应命名为'texture_diffuseN',其中N是从1到MAX_SAMPLER_NUMBER的连续数字。
        // 其他纹理也适用相同的命名约定,下面的列表总结了各个纹理的命名方式:
        // 漫反射纹理:texture_diffuseN
        // 高光反射纹理:texture_specularN
        // 法线纹理:texture_normalN

        // 1. 漫反射贴图
        vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
        textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
        // 2. 镜面反射贴图
        vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
        textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
        // 3. 法线贴图
        std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
        textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
        // 4. 视差贴图
        std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
        textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());

        // 返回从提取的网格数据创建的网格对象。
        return Mesh(vertices, indices, textures);
    }

    // 检查给定类型的所有材质纹理,并在尚未加载时加载纹理。
    // 所需的信息以 Texture 结构体的形式返回。
    vector<Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type, string typeName)
    {
        vector<Texture> textures;
        for (unsigned int i = 0; i < mat->GetTextureCount(type); i++)
        {
            aiString str;
            mat->GetTexture(type, i, &str);
            // 检查纹理是否已加载,如果是,则继续下一次迭代:跳过加载新纹理。
            bool skip = false;
            for (unsigned int j = 0; j < textures_loaded.size(); j++)
            {
                if (std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
                {
                    textures.push_back(textures_loaded[j]);
                    skip = true; // 已经加载了具有相同文件路径的纹理,请继续下一个(优化)。
                    break;
                }
            }
            if (!skip)
            {   // 如果纹理尚未加载,请加载它。
                Texture texture;
                texture.id = TextureFromFile(str.C_Str(), this->directory);
                texture.type = typeName;
                texture.path = str.C_Str();
                textures.push_back(texture);
                textures_loaded.push_back(texture);  // 将其作为整个模型加载的纹理存储,以确保不会不必要地加载重复的纹理。
            }
        }
        return textures;
    }
};


unsigned int TextureFromFile(const char* path, const string& directory, bool gamma)
{
    string filename = string(path);
    filename = directory + '/' + filename;

    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char* data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        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_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}
#endif

stb_image.h头文件下载地址:

https://github.com/nothings/stb/blob/master/stb_image.h

(需要科学上网)

stb_image_S.cpp源文件代码:

/* 预处理器会修改头文件,让其只包含相关的函数定义源码 */
#define STB_IMAGE_IMPLEMENTATION
/* 图像加载头文件 */
#include "stb_image.h"
StencilTesting.cpp源文件代码:
/*
 *
 * OpenGL学习——19.模板测试
 * 2024年3月7日
 *
 */



#include <iostream>

#include "glad/glad.h"
#include "GLFW/glfw3.h"
#include "glad/glad.c"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

/* 着色器头文件 */
#include "SHADER_H.h"
/* 摄影机头文件 */
#include "camera.h"
/* 图像加载头文件 */
#include "stb_image.h"
/* 模型头文件 */
#include "MODEL_H.h"

#pragma comment(lib, "glfw3.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "assimp-vc140-mt.lib")

/* 屏幕宽度 */
const int screenWidth = 1600;
/* 屏幕高度 */
const int screenHeight = 900;

/* 摄影机初始位置 */
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = screenWidth / 2.0f;
float lastY = screenHeight / 2.0f;
bool firstMouse = true;

/* 两帧之间的时间 */
float deltaTime = 0.0f;
float lastFrame = 0.0f;

/* 灯光位置 */
glm::vec3 lightPos(0.0f, 0.0f, -2.0f);

/* 这是framebuffer_size_callback函数的定义,该函数用于处理窗口大小变化的回调函数。当窗口的大小发生变化时,该函数会被调用,
它会设置OpenGL视口(Viewport)的大小,以确保渲染结果正确显示。 */
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);
}

/* 处理用户输入 */
void processInput(GLFWwindow* window)
{
    /* 退出 */
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);

    /* 前进 */
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        camera.ProcessKeyboard(FORWARD, deltaTime);
    /* 后退 */
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        camera.ProcessKeyboard(BACKWARD, deltaTime);
    /* 左移 */
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        camera.ProcessKeyboard(LEFT, deltaTime);
    /* 右移 */
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        camera.ProcessKeyboard(RIGHT, deltaTime);
    /* 上升 */
    if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
        camera.ProcessKeyboard(RISE, deltaTime);
    /* 下降 */
    if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
        camera.ProcessKeyboard(FALL, deltaTime);
}

/* 鼠标回调函数 */
void mouse_callback(GLFWwindow* window, double xposIn, double yposIn)
{
    float xpos = static_cast<float>(xposIn);
    float ypos = static_cast<float>(yposIn);

    if (firstMouse)
    {
        lastX = xpos;
        lastY = ypos;
        firstMouse = false;
    }

    float xoffset = xpos - lastX;
    float yoffset = lastY - ypos;

    lastX = xpos;
    lastY = ypos;

    camera.ProcessMouseMovement(xoffset, yoffset);
}

/* 滚轮回调函数 */
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
    camera.ProcessMouseScroll(static_cast<float>(yoffset));
}

/* 纹理加载函数 */
unsigned int loadTexture(char const* path)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
        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_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}

int main()
{
    /* 这是GLFW库的初始化函数,用于初始化GLFW库的状态以及相关的系统资源。 */
    glfwInit();

    /* 下面两行代码表示使用OpenGL“3.3”版本的功能 */
    /* 这行代码设置OpenGL上下文的主版本号为3。这意味着我们希望使用OpenGL “3.几”版本的功能。 */
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    /* 这行代码设置OpenGL上下文的次版本号为3。这表示我们希望使用OpenGL “几.3”版本的功能。 */
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

    /* 这行代码设置OpenGL的配置文件为核心配置文件(Core Profile)。核心配置文件是3.2及以上版本引入的,移除了一些已经被认为过时或不推荐使用的功能。 */
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    /* 这行代码的作用是设置OpenGL上下文为向前兼容模式,但该程序无需向后兼容,所以注释掉 */
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    /* 这行代码创建一个名为"LearnOpenGL"的窗口,窗口的初始宽度为800像素,高度为600像素。最后两个参数为可选参数,用于指定窗口的监视器(显示器),
    在此处设置为NULL表示使用默认的显示器。函数返回一个指向GLFWwindow结构的指针,用于表示创建的窗口。 */
    GLFWwindow* window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", NULL, NULL);

    /* 这是一个条件语句,判断窗口是否成功创建。如果窗口创建失败,即窗口指针为NULL,执行if语句块内的代码。 */
    if (window == NULL)
    {
        /* 这行代码使用C++标准输出流将字符串"Failed to create GLFW window"打印到控制台。即打印出“GLFW窗口创建失败”的错误信息。 */
        std::cout << "Failed to create GLFW window" << std::endl;

        /* 这行代码用于终止GLFW库的运行,释放相关的系统资源。 */
        glfwTerminate();

        /* 这是main函数的返回语句,表示程序异常结束并返回-1作为退出码。在C++中,返回负数通常表示程序发生错误或异常退出。 */
        return -1;
    }

    /* 这行代码将指定的窗口的上下文设置为当前上下文。它告诉OpenGL将所有渲染操作应用于指定窗口的绘图缓冲区。
     * 这是为了确保OpenGL在正确的窗口上进行渲染。 */
    glfwMakeContextCurrent(window);

    /* 这是一个条件语句,用于检查GLAD库的初始化是否成功。gladLoadGLLoader函数是GLAD库提供的函数,用于加载OpenGL函数指针。
    glfwGetProcAddress函数是GLFW库提供的函数,用于获取特定OpenGL函数的地址。这行代码将glfwGetProcAddress函数的返回值转换为GLADloadproc类型,
    并将其作为参数传递给gladLoadGLLoader函数。如果初始化失败,即返回值为假(NULL),则执行if语句块内的代码。 */
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        /* 这行代码使用C++标准输出流将字符串"Failed to initialize GLAD"打印到控制台。即打印出“GLAD库初始化失败”的错误信息。 */
        std::cout << "Failed to initialize GLAD" << std::endl;

        /* 这是main函数的返回语句,表示程序异常结束并返回-1作为退出码。在C++中,返回负数通常表示程序发生错误或异常退出。 */
        return -1;
    }

    /* 渲染之前必须告诉OpenGL渲染窗口的尺寸大小,即视口(Viewport),这样OpenGL才只能知道怎样根据窗口大小显示数据和坐标。 */
    /* 这行代码设置窗口的维度(Dimension),glViewport函数前两个参数控制窗口左下角的位置。第三个和第四个参数控制渲染窗口的宽度和高度(像素)。 */
    /* 实际上也可以将视口的维度设置为比GLFW的维度小,这样子之后所有的OpenGL渲染将会在一个更小的窗口中显示,
     * 这样子的话我们也可以将一些其它元素显示在OpenGL视口之外。 */
    glViewport(0, 0, screenWidth, screenHeight);

    /* 这行代码设置了窗口大小变化时的回调函数,即当窗口大小发生变化时,framebuffer_size_callback函数会被调用。 */
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    /* 鼠标回调 */
    glfwSetCursorPosCallback(window, mouse_callback);
    /* 滚轮回调 */
    glfwSetScrollCallback(window, scroll_callback);
    /* 隐藏光标 */
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    /* 开启深度测试 */
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    /* 开启模板测试 */
    glEnable(GL_STENCIL_TEST);
    glStencilOp(GL_KEEP, GL_REPLACE, GL_REPLACE);

    /* 着色器文件 */
    Shader lightingShader("vs_multiple_lights.txt", "fs_multiple_lights.txt");
    Shader lightCubeShader("vs_light_cube.txt", "fs_light_cube.txt");
    Shader SingleColorShader("vs_single_color.txt", "fs_single_color.txt");
    /* 模型文件 */
    Model ourModel("resources/models/nanosuit/nanosuit.obj");

    /* 定义顶点坐标数据的数组 */
    float vertices[] =
    {
        // 顶点坐标           // 法向量             //纹理坐标
        // +X面
         0.5f,  0.5f, -0.5f,   1.0f,  0.0f,  0.0f,   1.0f, 1.0f,   // 右上角
         0.5f, -0.5f, -0.5f,   1.0f,  0.0f,  0.0f,   1.0f, 0.0f,   // 右下角
         0.5f, -0.5f,  0.5f,   1.0f,  0.0f,  0.0f,   0.0f, 0.0f,   // 左下角
         0.5f,  0.5f,  0.5f,   1.0f,  0.0f,  0.0f,   0.0f, 1.0f,   // 左上角
         // -X面              
         -0.5f,  0.5f,  0.5f,  -1.0f,  0.0f,  0.0f,   1.0f, 1.0f,   // 右上角
         -0.5f, -0.5f,  0.5f,  -1.0f,  0.0f,  0.0f,   1.0f, 0.0f,   // 右下角
         -0.5f, -0.5f, -0.5f,  -1.0f,  0.0f,  0.0f,   0.0f, 0.0f,   // 左下角
         -0.5f,  0.5f, -0.5f,  -1.0f,  0.0f,  0.0f,   0.0f, 1.0f,   // 左上角
         // +Y面              
          0.5f,  0.5f, -0.5f,   0.0f,  1.0f,  0.0f,   1.0f, 1.0f,   // 右上角
          0.5f,  0.5f,  0.5f,   0.0f,  1.0f,  0.0f,   1.0f, 0.0f,   // 右下角
         -0.5f,  0.5f,  0.5f,   0.0f,  1.0f,  0.0f,   0.0f, 0.0f,   // 左下角
         -0.5f,  0.5f, -0.5f,   0.0f,  1.0f,  0.0f,   0.0f, 1.0f,   // 左上角
         // -Y面              
          0.5f, -0.5f,  0.5f,   0.0f, -1.0f,  0.0f,   1.0f, 1.0f,   // 右上角
          0.5f, -0.5f, -0.5f,   0.0f, -1.0f,  0.0f,   1.0f, 0.0f,   // 右下角
         -0.5f, -0.5f, -0.5f,   0.0f, -1.0f,  0.0f,   0.0f, 0.0f,   // 左下角
         -0.5f, -0.5f,  0.5f,   0.0f, -1.0f,  0.0f,   0.0f, 1.0f,   // 左上角
         // +Z面              
          0.5f,  0.5f,  0.5f,   0.0f,  0.0f,  1.0f,   1.0f, 1.0f,   // 右上角
          0.5f, -0.5f,  0.5f,   0.0f,  0.0f,  1.0f,   1.0f, 0.0f,   // 右下角
         -0.5f, -0.5f,  0.5f,   0.0f,  0.0f,  1.0f,   0.0f, 0.0f,   // 左下角
         -0.5f,  0.5f,  0.5f,   0.0f,  0.0f,  1.0f,   0.0f, 1.0f,   // 左上角
         // -Z面              
         -0.5f,  0.5f, -0.5f,   0.0f,  0.0f, -1.0f,   1.0f, 1.0f,   // 右上角
         -0.5f, -0.5f, -0.5f,   0.0f,  0.0f, -1.0f,   1.0f, 0.0f,   // 右下角
          0.5f, -0.5f, -0.5f,   0.0f,  0.0f, -1.0f,   0.0f, 0.0f,   // 左下角
          0.5f,  0.5f, -0.5f,   0.0f,  0.0f, -1.0f,   0.0f, 1.0f    // 左上角
    };

    /* 定义索引数据的数组 */
    unsigned int indices[] =
    {
        // 注意索引从0开始! 此例的索引(0,1,2,3)就是顶点数组vertices的下标,这样可以由下标代表顶点组合成矩形
        // +X面
         0,  1,  3, // 第一个三角形
         1,  2,  3, // 第二个三角形
         // -X面
          4,  5,  7, // 第一个三角形
          5,  6,  7, // 第二个三角形
          // +Y面
           8,  9, 11, // 第一个三角形
           9, 10, 11, // 第二个三角形
           // -Y面
           12, 13, 15, // 第一个三角形
           13, 14, 15, // 第二个三角形
           // +Z面
           16, 17, 19, // 第一个三角形
           17, 18, 19, // 第二个三角形
           // -Z面
           20, 21, 23, // 第一个三角形
           21, 22, 23, // 第二个三角形
    };

    /* 方块的位置 */
    glm::vec3 cubePositions[] = {
        glm::vec3(0.0f,  0.0f,  0.0f),
        glm::vec3(2.0f,  5.0f, -7.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -6.3f),
        glm::vec3(2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3(1.3f, -2.0f, -2.5f),
        glm::vec3(1.5f,  2.0f, -4.5f),
        glm::vec3(3.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
    };

    /* 光源的位置 */
    glm::vec3 pointLightPositions[] = {
        glm::vec3(0.7f,  0.2f,  2.0f),
        glm::vec3(2.3f, -3.3f, -4.0f),
        glm::vec3(-4.0f,  2.0f, -12.0f),
        glm::vec3(0.0f,  0.0f, -3.0f)
    };

    /* 光源的颜色 */
    glm::vec3 pointLightColors[] = {
        glm::vec3(1.0f,  1.0f,  1.0f),
        glm::vec3(1.0f,  0.0f,  0.0f),
        glm::vec3(0.0f,  1.0f,  0.0f),
        glm::vec3(0.0f,  0.0f,  1.0f)
    };

    /* 模型的位置 */
    glm::vec3 modelPositions[] = {
        glm::vec3(4.0f, 0.0f, 1.0f),
        glm::vec3(-5.0f, 0.0f, -1.0f)
    };

    /* 创建顶点数组对象(cubeVAO)(lightCubeVAO),顶点缓冲对象(VBO)和元素缓冲对象(EBO) */
    unsigned int cubeVAO, lightCubeVAO;
    unsigned int VBO;
    unsigned int EBO;

    glGenVertexArrays(1, &cubeVAO);
    glGenVertexArrays(1, &lightCubeVAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    /* cubeVAO */
    /* 绑定顶点数组对象,顶点缓冲对象和元素缓冲对象 */
    glBindVertexArray(cubeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);

    /* 将顶点数据复制到顶点缓冲对象中 */
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* 将索引数据复制到元素缓冲对象中 */
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    /* 设置顶点属性指针,指定如何解释顶点数据 */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); // 顶点坐标
    /* 启用顶点属性 */
    glEnableVertexAttribArray(0);

    /* 设置顶点属性指针,指定如何解释顶点数据 */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); // 法向量
    /* 启用顶点属性 */
    glEnableVertexAttribArray(1);

    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);

    /* lightCubeVAO */
    /* 绑定顶点数组对象,顶点缓冲对象和元素缓冲对象 */
    glBindVertexArray(lightCubeVAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);

    /* 将顶点数据复制到顶点缓冲对象中 */
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* 将索引数据复制到元素缓冲对象中 */
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    /* 设置顶点属性指针,指定如何解释顶点数据 */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); // 顶点坐标
    /* 启用顶点属性 */
    glEnableVertexAttribArray(0);

    /* 解绑顶点数组对象,顶点缓冲对象和元素缓冲对象 */
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    /* 告诉stb_image.h在加载纹理时翻转图像的y轴 */
    stbi_set_flip_vertically_on_load(true);

    /* 材质 */
    unsigned int diffuseMap = loadTexture("resources/images/container2.png");
    unsigned int specularMap = loadTexture("resources/images/container2_specular.png");

    lightingShader.use();
    /* 材质漫反射 */
    lightingShader.setInt("material.diffuse", 0);
    /* 材质镜面反射 */
    lightingShader.setInt("material.specular", 1);

    /* 这是一个循环,只要窗口没有被要求关闭,就会一直执行循环内的代码。 */
    while (!glfwWindowShouldClose(window))
    {
        float currentFrame = static_cast<float>(glfwGetTime());
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        /* 这行代码调用processInput函数,用于处理用户输入。 */
        processInput(window);

        /* 这行代码设置清空颜色缓冲区时的颜色。在这个示例中,将颜色设置为浅蓝色。 */
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        /* 清除颜色缓冲、深度缓冲、模板缓冲,以准备进行下一帧的渲染。 */
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

        /* 使用着色器程序 */
        lightingShader.use();

        /* 摄影机位置 */
        lightingShader.setVec3("viewPos", camera.Position);

        /* 灯光特性 */
        glm::vec3 lightColor;
        lightColor.x = static_cast<float>(1.0f);
        lightColor.y = static_cast<float>(1.0f);
        lightColor.z = static_cast<float>(1.0f);
        glm::vec3 diffuseColor = lightColor * glm::vec3(0.8f);
        glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f);

        /* 平行光 */
        glm::vec3 sun_direction(-(float)sin(glfwGetTime()), 0.0f, -(float)cos(glfwGetTime()));
        lightingShader.setVec3("dirLight.direction", sun_direction);

        lightingShader.setVec3("dirLight.ambient", ambientColor);
        lightingShader.setVec3("dirLight.diffuse", diffuseColor);
        lightingShader.setVec3("dirLight.specular", 1.0f, 1.0f, 1.0f);

        /* 点光源 */
        for (int i = 0; i < 4; i++)
        {
            std::stringstream ss;

            ss.str(""); // 清空字符串流
            ss << "pointLights[" << i << "].position";
            std::string position = ss.str();

            ss.str(""); // 清空字符串流
            ss << "pointLights[" << i << "].ambient";
            std::string ambient = ss.str();

            ss.str(""); // 清空字符串流
            ss << "pointLights[" << i << "].diffuse";
            std::string diffuse = ss.str();

            ss.str(""); // 清空字符串流
            ss << "pointLights[" << i << "].specular";
            std::string specular = ss.str();

            ss.str(""); // 清空字符串流
            ss << "pointLights[" << i << "].constant";
            std::string constant = ss.str();

            ss.str(""); // 清空字符串流
            ss << "pointLights[" << i << "].linear";
            std::string linear = ss.str();

            ss.str(""); // 清空字符串流
            ss << "pointLights[" << i << "].quadratic";
            std::string quadratic = ss.str();

            /* 灯光特性 */
            glm::vec3 lightColor = pointLightColors[i];
            glm::vec3 diffuseColor = lightColor * glm::vec3(0.8f);
            glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f);

            /* 光照属性设置 */
            lightingShader.setVec3(position.c_str(), pointLightPositions[i]);
            lightingShader.setVec3(ambient.c_str(), ambientColor);
            lightingShader.setVec3(diffuse.c_str(), diffuseColor);
            lightingShader.setVec3(specular.c_str(), 1.0f, 1.0f, 1.0f);
            /* 衰减 */
            lightingShader.setFloat(constant.c_str(), 1.0f);
            lightingShader.setFloat(linear.c_str(), 0.09f);
            lightingShader.setFloat(quadratic.c_str(), 0.032f);
        }

        /* 聚光 */
        lightingShader.setVec3("spotLight.position", camera.Position);
        lightingShader.setVec3("spotLight.direction", camera.Front);
        lightingShader.setFloat("spotLight.cutOff", glm::cos(glm::radians(17.0f)));
        lightingShader.setFloat("spotLight.outerCutOff", glm::cos(glm::radians(20.0f)));
        lightingShader.setVec3("spotLight.ambient", ambientColor);
        lightingShader.setVec3("spotLight.diffuse", diffuseColor);
        lightingShader.setVec3("spotLight.specular", 1.0f, 1.0f, 1.0f);
        /* 衰减 */
        lightingShader.setFloat("spotLight.constant", 1.0f);
        lightingShader.setFloat("spotLight.linear", 0.09f);
        lightingShader.setFloat("spotLight.quadratic", 0.032f);

        /* 材质特性 */
        lightingShader.setFloat("material.shininess", 64.0f);

        /* 视角矩阵 */
        glm::mat4 view = glm::mat4(1.0f);
        view = camera.GetViewMatrix();

        /* 透视矩阵 */
        glm::mat4 projection = glm::mat4(1.0f);
        projection = glm::perspective(glm::radians(camera.Zoom), (float)screenWidth / (float)screenHeight, 0.1f, 100.0f);

        /* 将视图矩阵的值传递给对应的uniform */
        lightingShader.setMat4("view", view);
        /* 将投影矩阵的值传递给对应的uniform */
        lightingShader.setMat4("projection", projection);

        /* 使用着色器程序 */
        lightCubeShader.use();
        /* 将投影矩阵的值传递给对应的uniform */
        lightCubeShader.setMat4("projection", projection);
        /* 将视图矩阵的值传递给对应的uniform */
        lightCubeShader.setMat4("view", view);

        /* 使用着色器程序 */
        SingleColorShader.use();
        SingleColorShader.setMat4("view", view);
        SingleColorShader.setMat4("projection", projection);

        /* 模型矩阵 */
        glm::mat4 model;

        /* 使用着色器 */
        lightingShader.use();

        /* 绑定顶点数组对象 */
        glBindVertexArray(cubeVAO);
        for (unsigned int i = 0; i < 10; i++)
        {
            /* 计算每个对象的模型矩阵,并在绘制之前将其传递给着色器 */
            model = glm::mat4(1.0f);
            /* 移动 */
            model = glm::translate(model, cubePositions[i]);
            /* 旋转 */
            model = glm::rotate(model, (float)glfwGetTime() * (i + 1) / 5, glm::vec3(-0.5f + ((float)i / 20.0), 1.0f, 0.0f));

            /* 将模型矩阵的值传递给对应的uniform */
            lightingShader.setMat4("model", model);

            /* 绑定漫反射贴图 */
            glActiveTexture(GL_TEXTURE0 + 0);
            glBindTexture(GL_TEXTURE_2D, diffuseMap);
            /* 绑定镜面反射贴图 */
            glActiveTexture(GL_TEXTURE0 + 1);
            glBindTexture(GL_TEXTURE_2D, specularMap);

            /* 绘制矩形 */
            glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
        }

        /* 使用着色器 */
        lightCubeShader.use();

        for (unsigned int i = 0; i < 4; i++)
        {
            /* 灯方块颜色 */
            lightCubeShader.setVec3("lightCubeColor", pointLightColors[i]);

            /* 赋值为单位矩阵 */
            model = glm::mat4(1.0f);
            /* 移动 */
            model = glm::translate(model, pointLightPositions[i]);
            /* 缩放 */
            model = glm::scale(model, glm::vec3(0.2f));

            /* 将模型矩阵的值传递给对应的uniform */
            lightCubeShader.setMat4("model", model);

            /* 绑定顶点数组对象 */
            glBindVertexArray(lightCubeVAO);
            /* 绘制矩形 */
            glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
        }

        /* 模型及其边框 */
        for (unsigned int i = 0; i < 2; i++)
        {
            /* 掩码:设定部分位上的模板值可以启用,例如0x0B(十进制为11,二进制为1101),二进制从右往左数,只有第1,3,4位上的值启用,第2位上的值被屏蔽 */
            /* 设置模板掩码为2(二进制:10),只允许第2位被写入模板缓冲区,第1位为0,被屏蔽 */
            glStencilMask(2);

            /* 始终通过模板测试,并且参考值为2 */
            glStencilFunc(GL_ALWAYS, 2, 0xFF);

            /* 使用着色器程序 */
            lightingShader.use();

            // 绘制本模型
            model = glm::mat4(1.0f);
            model = glm::translate(model, modelPositions[i]);
            model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f));
            lightingShader.setMat4("model", model);
            ourModel.Draw(lightingShader);

            /* 设置模板掩码为1(二进制:1),只允许第1位被写入模板缓冲区 */
            glStencilMask(1);

            /* 始终通过模板测试,并且参考值为1 */
            glStencilFunc(GL_ALWAYS, 1, 0xFF);

            /* 另外的模型 */
            for (unsigned int j = 0; j < 2; j++)
            {
                /* 除本模型之外 */
                if (i != j)
                {
                    /* 使用着色器程序 */
                    lightingShader.use();

                    // 绘制另外的模型
                    model = glm::mat4(1.0f);
                    model = glm::translate(model, modelPositions[j]);
                    model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f));
                    lightingShader.setMat4("model", model);
                    ourModel.Draw(lightingShader);
                }
            }

            /* 此代码是否注释可以决定模型之间能否互相透视看见边框,注释时不能互相透视,不注释时可以互相透视 */
            //glDisable(GL_DEPTH_TEST);

            /* 模板值等于1的通过模板测试 */
            glStencilFunc(GL_EQUAL, 1, 0xFF);
            
            /* 使用着色器程序 */
            SingleColorShader.use();

            /* 模型轮廓 */
            model = glm::mat4(1.0f);
            model = glm::translate(model, modelPositions[i]);
            model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f));
            SingleColorShader.setMat4("model", model);
            /* 绘制一部分本模型的边框 */
            ourModel.Draw(SingleColorShader);

            /* 禁用深度缓冲,为了边框能够被透视 */
            glDisable(GL_DEPTH_TEST);
            
            /* 模板值等于0的通过模板测试 */
            glStencilFunc(GL_EQUAL, 0, 0xFF);
            
            /* 绘制本模型剩下部分的边框 */
            ourModel.Draw(SingleColorShader);
            
            /* 启用深度测试 */
            glEnable(GL_DEPTH_TEST);

            /* 启用模板值各个位的修改 */
            glStencilMask(0xFF);
            /* 始终通过测试 */
            glStencilFunc(GL_ALWAYS, 0, 0xFF);
            /* 清除模板缓冲,确保每个模型都有独自的边框 */
            glClear(GL_STENCIL_BUFFER_BIT);
        }

        /* 这行代码交换前后缓冲区,将当前帧的渲染结果显示到窗口上。 */
        glfwSwapBuffers(window);

        /* 这行代码处理窗口事件,例如键盘输入、鼠标移动等。它会检查是否有事件发生并触发相应的回调函数。 */
        glfwPollEvents();
    }

    /* 删除顶点数组对象 */
    glDeleteVertexArrays(1, &cubeVAO);
    /* 删除顶点缓冲对象 */
    glDeleteBuffers(1, &VBO);
    /* 删除元素缓冲对象 */
    glDeleteBuffers(1, &EBO);
    /* 删除着色器程序 */
    lightingShader.deleteProgram();
    lightCubeShader.deleteProgram();

    /* 这行代码终止GLFW库的运行,释放相关的系统资源。 */
    glfwTerminate();

    /* 程序结束,返回0 */
    return 0;
}
运行结果:

每个模型都有单独的边框,并且边框可以被其它模型遮挡(模型之间具有深度效果)。同时,也可以通过除模型之外的物体直接透视边框。(模型边框与其它物体之间不具有深度效果)

注意!该程序操作方式如下:

WSAD键控制前后左右移动,空格键飞行,shift键下降,
鼠标移动控制视角,鼠标滚轮控制视野缩放。
Esc键退出程序。

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
另外在运行程序时,请打开键盘的英文大写锁定,
否则按shift之后会跳出中文输入法。
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

无论您是OpenGL的初学者还是经验丰富的开发者,我都鼓励您在下方的评论区与我互动。如果您有关于模板测试的实际应用案例,或者在使用模板测试时遇到的挑战和解决方案,都非常欢迎您分享。您的经验和见解将为其他读者提供宝贵的学习资源。
模板测试在图形应用程序中具有广泛的应用。例如,您可能正在开发一个游戏,在游戏中使用模板测试来创建碰撞检测或特定区域的可见性控制。或者您可能正在构建一个可视化应用程序,使用模板测试来实现遮罩效果或镜像反射效果。无论您面临的挑战是什么,我都希望能够与您一起探讨解决方案,并共同学习如何优化和改进模板测试的应用。
如果您对本文的内容有任何疑问或需要进一步的解释,请务必告诉我。我将竭诚为您提供帮助,并确保您对模板测试的概念和应用有一个清晰的理解。
我期待与您的互动,共同探索OpenGL模板测试的奥秘,以及如何将其应用于您的图形应用程序中。让我们一起创造出令人惊叹的视觉效果!

  • 24
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python的OpenGL库是一个用于渲染图形和实现3D图形应用的强大工具。如果你是一个初学者,以下是一些学习OpenGL的指南: 1. 学习基本的计算机图形学概念:在深入学习OpenGL之前,了解一些基本的计算机图形学概念是很重要的。你可以学习像坐标系、向量、矩阵变换等基础知识。 2. 学习Python语言基础:作为一个初学者,你需要先掌握Python的基本语法和编程概念。这将帮助你更好地理解和使用OpenGL库。 3. 安装OpenGL库:在开始之前,你需要确保你的计算机上已经安装了OpenGL库。你可以使用pip来安装PyOpenGL库。 4. 学习OpenGL的核心知识:一旦你准备好了,可以开始学习OpenGL的核心知识,如顶点缓冲对象(VBO)、着色器(programs)、着色器语言(GLSL)等。掌握这些基本概念对于理解和使用OpenGL非常重要。 5. 编写简单的OpenGL程序:接下来,你可以开始编写一些简单的OpenGL程序来实践所学的知识。你可以从简单的绘制一些基本图形开始,然后逐渐扩展到更复杂的场景和效果。 6. 学习OpenGL的高级特性:一旦你熟悉了OpenGL的基本知识,你可以探索一些更高级的主题,如光照、纹理映射、深度测试、投影等。这将帮助你创建更逼真和交互式的3D图形应用。 7. 参考文档和教程:除了上述的自学方法外,你还可以参考一些优秀的OpenGL文档和教程。一些推荐的资源包括OpenGL官方文档、PyOpenGL官方文档、学习OpenGL的在线教程等。 记住,学习OpenGL需要时间和实践。通过不断地编写代码和实验,你将逐渐掌握OpenGL的技能并创建出令人惊叹的图形应用。祝你好运!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值