#include "stdafx.h"
#include "ObjMeshWriter.h"

#include "ObjMesh.h"

using namespace std;



namespace lib_geo
{


bool ObjMeshWriter::Save( const ObjMesh& mesh , const string& filename ) const
{
	ofstream ofs( filename.c_str() );
	if( !ofs.is_open() )
		return false;

	return SaveObjMain( mesh , ofs );
}

bool ObjMeshWriter::SaveStream( const ObjMesh& mesh , ostream& ost ) const
{
	return SaveObjMain( mesh , ost );
}

bool ObjMeshWriter::SaveObjMain( const ObjMesh& mesh , ostream& ost ) const
{
	// 頂点バッファ
	for (const lm::vec3f& v : mesh.m_Verts)
	{
		ost << "v " << v.x << " " << v.y << " " << v.z << endl;
	}

	// UVバッファ
	for(size_t i = 0; i < mesh.m_UVs.size(); ++i)
	{
		const lm::vec2f& uv = mesh.m_UVs[i];
		ost << "vt " << uv.x << " " << uv.y << endl;
	}

	// 法線バッファ
	for(size_t i = 0; i < mesh.m_Normals.size(); ++i)
	{
		const lm::vec3f& normal = mesh.m_Normals[i];
		ost << "vn " << normal.x << " " << normal.y << " " << normal.z << endl;
	}

	for(size_t i = 0 ; i < mesh.m_Faces.size(); ++i)
	{
		const ObjFace& face = mesh.m_Faces[i];
		if (face.m_IdxV.IsEmpty())
			continue;

		bool has_uv = !face.m_IdxUV.IsEmpty();
		bool has_n  = !face.m_IdxN.IsEmpty();

		ost << "f";
		for (size_t j = 0; j < face.m_IdxV.m_Count; ++i)
		{
			int vid, uvid, nid;

			vid = mesh.m_FaceBuf.m_FaceIdxV[face.m_IdxV.m_Offset + j];

			if( has_uv )
				uvid = mesh.m_FaceBuf.m_FaceIdxUV[face.m_IdxUV.m_Offset + j];

			if( has_n )
				nid = mesh.m_FaceBuf.m_FaceIdxN[face.m_IdxN.m_Offset + j];

			if( !has_uv && !has_n )
				ost << " " << vid+1;
			else if( has_uv )
				ost << " " << vid+1 << "/" << uvid+1;
			else if( has_n )
				ost << " " << vid+1 << "//" << nid+1;
			else
				ost << " " << vid+1 << "/" << uvid+1 << "/" << nid+1;
		}
		ost << endl;
	}

	return true;
}


}
