int saveMeshAsObjWithTexture(Mesh& mgtext, const string& filename) { size_t nVerts = mgtext.pointnum; size_t nfaces = mgtext.facenum; ofstream outfile; outfile.open(filename); if (!outfile) { std::cout << "file open failed. "; return -1; } string mtlname = filename; mtlname.erase(mtlname.end() - 4, mtlname.end()); ofstream mtl; mtl.open(mtlname + ".mtl"); if (!mtl) { std::cout << "file mtl open failed. "; return -1; } //mtl mtl << "# " << "# Wavefront material file " << "# Converted by Meshlab Group " << "# " << "newmtl material_0 " << "Ka 0.200000 0.200000 0.200000 " << "Kd 1.000000 1.000000 1.000000 " << "Ks 1.000000 1.000000 1.000000 " << "Tr 1.000000 " << "illum 2 " << "Ns 0.000000 " << "map_Kd material0000.png "; mtl.close(); //obj header outfile << "#### " << "# " << "# OBJ File Generated by Meshlab " << "# " << "#### " << "# Object out.obj " << "# " << "# Vertices: " << nVerts << " " << "# Faces : " << nfaces << " " << "# " << "#### " << "mtllib ./out.mtl "; // Vertices for (size_t i = 0; i < nVerts; i++) { outfile << setiosflags(ios::fixed) << setprecision(6) << "vn " << mgtext.normals[i].x << " " << mgtext.normals[i].y << " " << mgtext.normals[i].z << " " << "vt " << mgtext.point_uv_vect[i].x << " " << mgtext.point_uv_vect[i].y << " " << "v " << mgtext.point_vect[i].x << " " << mgtext.point_vect[i].y << " " << mgtext.point_vect[i].z << " "; } outfile << " "; outfile << "usemtl material_0 "; for (size_t i = 0; i < nfaces; i++) { outfile << "f " << mgtext.face[3 * i] + 1 << "/" << mgtext.face[3 * i] + 1 << "/" << mgtext.face[3 * i] + 1 << " " << mgtext.face[3 * i + 1] + 1 << "/" << mgtext.face[3 * i + 1] + 1 << "/" << mgtext.face[3 * i + 1] + 1 << " " << mgtext.face[3 * i + 2] + 1 << "/" << mgtext.face[3 * i + 2] + 1 << "/" << mgtext.face[3 * i + 2] + 1 << " "; } outfile << "# End of File "; outfile.close(); return 0; }