ccdemos/common_ply.h
author Radek Brich <radek.brich@devl.cz>
Mon, 21 Apr 2008 08:47:36 +0200
branchpyrit
changeset 74 09aedbf5f95f
parent 72 7c3f38dff082
child 80 907929fa9b59
permissions -rw-r--r--
kd-tree traversal - avoid dynamic memory allocation use minimum storage size for KdNode (8B on 32bit cpu) vector.h - add division operator, fix semicolons

#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);

		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();
}