diff --git a/mesh.h b/mesh.h index e61e3b5..1f6ab6e 100644 --- a/mesh.h +++ b/mesh.h @@ -27,17 +27,17 @@ struct Mesh std::vector tangents; std::vector indiceGroups; - bool hasNormals() + bool hasNormals() const { return normals.size() != 0; } - bool hasTexCoords() + bool hasTexCoords() const { return texCoords.size() != 0; } - bool hasTangents() + bool hasTangents() const { return tangents.size() != 0; } diff --git a/meshbuilder.cpp b/meshbuilder.cpp index 0640898..a21b31d 100644 --- a/meshbuilder.cpp +++ b/meshbuilder.cpp @@ -1,5 +1,6 @@ #include "meshbuilder.h" #include +#include void MeshBuilder::addPosition(float x, float y, float z) { @@ -81,6 +82,71 @@ int MeshBuilder::getNbGroups() return indiceGroups.size(); } +bool MeshBuilder::operator() (const int& vertId1, const int& vertId2) const +{ + if(positions[vertId1] != positions[vertId2]) + return (positions[vertId1].x + positions[vertId1].y + positions[vertId1].z) > (positions[vertId2].x + positions[vertId2].y + positions[vertId2].z); + if(hasTexCoords()) + { + if(texCoords[vertId1] != texCoords[vertId2]) + return (texCoords[vertId1].x + texCoords[vertId1].y) > (texCoords[vertId2].x + texCoords[vertId2].y); + } + if(hasNormals()) + { + if(normals[vertId1] != normals[vertId2]) + return (normals[vertId1].x + normals[vertId1].y + normals[vertId1].z) > (normals[vertId2].x + normals[vertId2].y + normals[vertId2].z); + } + return false; +} + +void MeshBuilder::mergeVertices() +{ + std::vector swapped; + std::set vertexSet; + + int size = positions.size(); + + for(Group &g : indiceGroups) + for(int i=0; i::iterator,bool> ret = vertexSet.insert(g.indices[i]); + if(!ret.second) // duplicate found + { + // updating indices references + int toDelete = g.indices[i]; + swapped.push_back(toDelete); + g.indices[i] = *(ret.first); + // deleting the duplicate + positions[toDelete] = positions.back(); + positions.pop_back(); + if(hasTexCoords()) + { + texCoords[toDelete] = texCoords.back(); + texCoords.pop_back(); + } + if(hasNormals()) + { + normals[toDelete] = normals.back(); + normals.pop_back(); + } + if(hasTangents()) + { + tangents[toDelete] = tangents.back(); + tangents.pop_back(); + } + } + } + + fprintf(stdout, "found %d vertex duplicates\n", swapped.size()); + + for(Group &g : indiceGroups) + for(int i=0; i= positions.size()) + g.indices[i] = swapped[size - g.indices[i]]; + } +} + void MeshBuilder::computeNormals() { normals.resize(positions.size()); diff --git a/meshbuilder.h b/meshbuilder.h index 90334fe..3487b3e 100644 --- a/meshbuilder.h +++ b/meshbuilder.h @@ -26,6 +26,9 @@ public: void setCurrentGroupMaterial(Material* myMaterial); int getNbGroups(); + // merge same vertices + void mergeVertices(); + bool operator() (const int& vertId1, const int& vertId2) const; // require positions and indices void computeNormals(); // require normals and texCoord