ccdemos/common_ply.h
author Radek Brich <radek.brich@devl.cz>
Tue, 29 Apr 2008 23:31:08 +0200
branchpyrit
changeset 90 f6a72eb99631
parent 80 907929fa9b59
child 91 9d66d323c354
permissions -rw-r--r--
rename Python module from 'raytracer' to 'pyrit' improve Python binding: - new objects: Container, Octree, KdTree, Shape, Pixmap, Sampler, DefaultSampler - all shapes are now subclasses of Shape - clean, remove redundant Getattr's - Raytracer render method now just wraps C++ method without doing any additional work adjust all demos for changes in Python binding, remove PIL dependency add demo_PIL.py as a example of pyrit + PIL usage render_nff.py now either loads file given as a argument or reads input from stdin otherwise fix bug in pixmap float to char conversion

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

		// check for invalid faces and ignore them
		if (vertices[v1]->P == vertices[v2]->P
		 || vertices[v1]->P == vertices[v3]->P
		 || vertices[v2]->P == vertices[v3]->P)
		{
			f.ignore(1000,'\n');
			continue;
		}

		face = new Triangle(vertices[v1], vertices[v3], vertices[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();
}