#include "ObjExporter.h" #include "SceneEntity.h" #include "Shape.h" #include "Geometry.h" using namespace std; // MAGIC of all bin exports #ifndef MAGIC #define MAGIC 0x827923 #endif #define BVH_VERSION 2.1 namespace CHCDemoEngine { static int currentIdx = 0; int ObjExporter::WriteGeometry(Geometry *geom, ofstream &ostream) { int numVertices; Vector3 *vertices = geom->GetVertices(numVertices); char str[100]; //cout << "vtx: " << numVertices << endl; for (int i = 0; i < numVertices; ++ i) { Vector3 v = vertices[i]; sprintf(str, "v %f %f %f\n", v.x, v.z, -v.y); ostream << str; } return numVertices; } bool ObjExporter::Export(const string &filename, Bvh *bvh) { cout << "Exporting obj to file '" << filename.c_str() << "'" << endl; ofstream ostream(filename.c_str()); if (!ostream.is_open()) { cerr << "Error: Cannot open file " << filename.c_str() << " for writing" << endl; return false; } int numVertices = 0; BvhNodeContainer nodes; bvh->CollectVirtualLeaves(bvh->GetStaticRoot(), nodes); cout << "writing " << nodes.size() << " objects ..." << endl; BvhNodeContainer::const_iterator it, it_end = nodes.end(); int j = 0; const int t = 1000; for (it = nodes.begin(); it != it_end; ++ it, ++ j) { if ((j % t) == (t - 1)) cout << j + 1 << endl; BvhNode *node = *it; int geometrySize; SceneEntity **entities = bvh->GetGeometry(node, geometrySize); for (int i = 0; i < geometrySize; ++ i) { ShapeContainer::iterator sit, send; entities[i]->GetLODLevel(0, sit, send); for (; sit != send; ++ sit) { Geometry *geom = (*sit)->GetGeometry(); int dummy; if (!geom->GetVertices(dummy)) { cerr << "error: geometry was deleted on loading, exporting obj failed" << endl; return false; } numVertices += WriteGeometry(geom, ostream); } } } cout << "finished" << endl; cout << "writing " << numVertices << " indices ..." << endl; for (int i = 0; i < numVertices; i += 3) { ostream << "f " << i + 1 << " " << i + 2 << " " << i + 3 << endl; } cout << "successfully exported obj" << endl; return true; } }