1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #pragma mark - Public #pragma mark -- 构造函数 Mesh::Mesh(std::vector<VertexInfo> vertices, std::vector<GLuint> indices, std::vector<TextureInfo> textures) { m_vertices = vertices; m_indices = indices; m_textures = textures; setupMesh(); }
#pragma mark -- 析构函数 Mesh::~Mesh() { }
#pragma mark -- 绘制网格
void Mesh::draw(Shader shader) { GLuint diffuseNr = 1; GLuint specularNr = 1; GLuint normalNr = 1; GLuint heightNr = 1; for (GLuint i = 0; i < m_textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); std::string number; std::string name = m_textures[i].type; if ("texture_diffuse" == name) { number = std::to_string(diffuseNr++); } else if ("texture_specular" == name) { number = std::to_string(specularNr++); } else if ("texture_normal" == name) { number = std::to_string(normalNr++); } else if ("texture_height" == name) { number = std::to_string(heightNr++); } shader.setUniformInt((name + number).c_str(), i); glBindTexture(GL_TEXTURE_2D, m_textures[i].tId); } glBindVertexArray(m_VAO); glDrawElements(GL_TRIANGLES, (GLsizei)m_indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); glActiveTexture(GL_TEXTURE0); }
#pragma mark - Private #pragma mark -- 设置网格数据 void Mesh::setupMesh() { glGenVertexArrays(1, &m_VAO); glGenBuffers(1, &m_VBO); glGenBuffers(1, &m_EBO); glBindVertexArray(m_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(VertexInfo), &m_vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indices.size() * sizeof(GLuint), &m_indices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexInfo), (void*)offsetof(VertexInfo, Position)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexInfo), (void *)offsetof(VertexInfo, Normal)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VertexInfo), (void*)offsetof(VertexInfo, TexCoords)); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(VertexInfo), (void*)offsetof(VertexInfo, Tangent)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(VertexInfo), (void*)offsetof(VertexInfo, Bitangent)); glBindVertexArray(0); }
|