From 7b455bd7dbfad05ad066a9caca457fb4c0078d62 Mon Sep 17 00:00:00 2001 From: Abe Pazos Date: Thu, 8 Jun 2017 12:33:52 +0200 Subject: [PATCH] Implement flatNormals() for polyhedrons and low-poly meshes --- libs/openFrameworks/3d/ofMesh.h | 3 +++ libs/openFrameworks/3d/ofMesh.inl | 45 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/libs/openFrameworks/3d/ofMesh.h b/libs/openFrameworks/3d/ofMesh.h index dcc89ad31ef..17418367a9a 100644 --- a/libs/openFrameworks/3d/ofMesh.h +++ b/libs/openFrameworks/3d/ofMesh.h @@ -353,6 +353,9 @@ class ofMesh_{ virtual bool usingNormals() const; void smoothNormals( float angle ); + + /// \brief Duplicates vertices and updates normals to get a low-poly look. + void flatNormals(); /// \} /// \name Faces diff --git a/libs/openFrameworks/3d/ofMesh.inl b/libs/openFrameworks/3d/ofMesh.inl index 5e87b6c5ce8..9289be38951 100644 --- a/libs/openFrameworks/3d/ofMesh.inl +++ b/libs/openFrameworks/3d/ofMesh.inl @@ -1797,6 +1797,51 @@ void ofMesh_::smoothNormals( float angle ) { } } +//-------------------------------------------------------------- +template +void ofMesh_::flatNormals() { + if( getMode() == OF_PRIMITIVE_TRIANGLES) { + + // get copy original mesh data + auto numIndices = getIndices().size(); + auto verts = getVertices(); + auto texCoords = getTexCoords(); + auto colors = getColors(); + + // remove all data to start from scratch + clear(); + + // add mesh data back, duplicating vertices and recalculating normals + N normal; + for(ofIndexType i = 0; i < numIndices; i++) { + ofIndexType indexCurr = getIndex(i); + + if(i % 3 == 0) { + ofIndexType indexNext1 = getIndex(i + 1); + ofIndexType indexNext2 = getIndex(i + 2); + auto e1 = verts[indexCurr] - verts[indexNext1]; + auto e2 = verts[indexNext2] - verts[indexNext1]; + normal = glm::normalize(glm::cross(e1, e2)); + } + + addIndex(i); + addNormal(normal); + + if(indexCurr < texCoords.size()) { + addTexCoord(texCoords[indexCurr]); + } + + if(indexCurr < verts.size()) { + addVertex(verts[indexCurr]); + } + + if(indexCurr < colors.size()) { + addColor(colors[indexCurr]); + } + } + } +} + // PLANE MESH //