#pragmaonce#ifndefMESH_H#defineMESH_H#include<glad/glad.h>// holds all OpenGL type declarations#include<glm/glm.hpp>#include<glm/gtc/matrix_transform.hpp>#include"Shader.h"#include<string>#include<fstream>#include<sstream>#include<iostream>#include<vector>usingnamespace std;structVertex{// position
glm::vec3 Position;// normal
glm::vec3 Normal;// texCoords
glm::vec2 TexCoords;};structTexture{unsignedint id;
string type;
string path;};classMesh{public:/* Mesh Data */
vector<Vertex> vertices;
vector<unsignedint> indices;
vector<Texture> textures;unsignedint VAO;/* Functions */// constructorMesh(vector<Vertex> vertices, vector<unsignedint> indices, vector<Texture> textures){this->vertices = vertices;this->indices = indices;this->textures = textures;// now that we have all the required data, set the vertex buffers and its attribute pointers.setupMesh();}// render the meshvoidDraw(Shader shader){//加载与绘制纹理unsignedint diffuseNr =1;unsignedint specularNr =1;for(unsignedint i =0; i < textures.size(); i++){glActiveTexture(GL_TEXTURE0 + i);// active proper texture unit before binding// retrieve texture number (the N in diffuse_textureN)//这里要绑定着色器里边的名字
string number;
string name = textures[i].type;if(name =="texture_diffuse")
number = std::to_string((longdouble)diffuseNr++);elseif(name =="texture_specular")
number = std::to_string((longdouble)specularNr++);// transfer unsigned int to stream// now set the sampler to the correct texture unitglUniform1i(glGetUniformLocation(shader.ID,(name + number).c_str()), i);// and finally bind the textureglBindTexture(GL_TEXTURE_2D, textures[i].id);}// draw meshglBindVertexArray(VAO);glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT,0);glBindVertexArray(0);// always good practice to set everything back to defaults once configured.glActiveTexture(GL_TEXTURE0);}private:/* Render data */unsignedint VBO, EBO;/* Functions */// initializes all the buffer objects/arraysvoidsetupMesh()//取代VAOset{glGenVertexArrays(1,&VAO);glGenBuffers(1,&VBO);glGenBuffers(1,&EBO);glBindVertexArray(VAO);glBindBuffer(GL_ARRAY_BUFFER, VBO);glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);//往显卡写值,分配显存空间GL_STATIC_DRAW表示,值不修改glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(Vertex),&vertices[0], GL_STATIC_DRAW);glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(unsignedint),&indices[0], GL_STATIC_DRAW);//告诉显卡,值的结构 positionglVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE,sizeof(Vertex),(void*)0);glEnableVertexAttribArray(0);//告诉显卡,值的结构 法线glVertexAttribPointer(1,3, GL_FLOAT, GL_FALSE,sizeof(Vertex),(void*)offsetof(Vertex, Normal));glEnableVertexAttribArray(1);//告诉显卡,值的结构 纹理坐标glVertexAttribPointer(2,2, GL_FLOAT, GL_FALSE,sizeof(Vertex),(void*)offsetof(Vertex, TexCoords));glEnableVertexAttribArray(2);glEnableVertexAttribArray(0);}};#endif