#include <iostream>
#include <fstream>
#include <iomanip>

void load_ply(Raytracer &rt, const char *filename, Material *mat, Vector3 scale, Vector3 transp)
{
	vector<NormalVertex*> vertices;
	vector<Vector3> normals;
	vector<int> vertex_face_num;
	ifstream f(filename);
	string token = "a";
	if (!f.is_open())
	{
		cout << "File not found: " << filename <<endl;
		exit(1);
	}
	// read header
	int vertex_num, face_num;
	while (token != "end_header")
	{
		f >> token;
		if (token == "element")
		{
			f >> token;
			if (token == "vertex")
				f >> vertex_num;
			if (token == "face")
				f >> face_num;
		}
		f.ignore(1000,'\n');
	}

	// read vertices
	Vector3 P;
	int num = vertex_num;
	while (num--)
	{
		f >> P.x >> P.y >> P.z;
		P.x = scale.x*P.x + transp.x;
		P.y = scale.y*P.y + transp.y;
		P.z = scale.z*P.z + transp.z;
		vertices.push_back(new NormalVertex(P));
		normals.push_back(Vector3());
		vertex_face_num.push_back(0);
		f.ignore(1000,'\n');
	}

	// read faces
	Triangle *face;
	int v1, v2, v3;
	while (face_num--)
	{
		f >> num;
		if (num != 3)
		{
			printf("ply error: faces of %d vertices not supported", num);
			continue;
		}
		f >> v1 >> v2 >> v3;
		face = new Triangle(vertices.at(v1), vertices.at(v3), vertices.at(v2), mat);
		rt.addshape(face);
		face->setSmooth();

		normals.at(v1) += face->getNormal();
		vertex_face_num.at(v1)++;
		normals.at(v2) += face->getNormal();
		vertex_face_num.at(v2)++;
		normals.at(v3) += face->getNormal();
		vertex_face_num.at(v3)++;
		f.ignore(1000,'\n');
	}

	for (int i = 0; i < vertex_num; i++)
		if (vertex_face_num.at(i))
		{
			normals.at(i) /= vertex_face_num.at(i);
			normals.at(i).normalize();
			vertices.at(i)->N = normals.at(i);
		}

	f.close();
}
