smooth triangles (aka Phong shading)
extend Python binding to support vertex normals and smooth triangles
make bunny.py and realtime_dragon smooth, and fix other demos for new triangle constructor
add Vector::operator/=
#!/usr/bin/python
# this demo needs bunny model from
# http://graphics.stanford.edu/data/3Dscanrep/
import sys
sys.path.append(open('ModulePath').read().strip())
from raytracer import Raytracer, Light, Sphere, Triangle, NormalVertex, Material
import Image
def LoadStanfordPlyFile(rt, mat, filename, scale):
	vertices = []
	normals = []
	vertex_face_num = []
	fp = file(filename)
	# read header
	tokens = (0,)
	while (tokens[0] != "end_header"):
		tokens = fp.readline().split()
		if (tokens[0] == "element"):
			if (tokens[1] == "vertex"):
				vertex_num = int(tokens[2])
			if (tokens[1] == "face"):
				face_num = int(tokens[2])
	# read vertices
	num = vertex_num
	while (num):
		tokens = fp.readline().split()
		v = [scale*float(x) for x in tokens[0:3]]
		v[0] = -v[0]-1
		v[1] = v[1]-3
		vertices.append(NormalVertex(tuple(v)))
		normals.append([0.,0.,0.])
		vertex_face_num.append(0)
		num -= 1
	# read faces
	while (face_num):
		tokens = fp.readline().split()
		if (tokens[0] != "3"):
			print "ply warning: faces of %d vertices not supported" % tokens[0]
		v = [vertices[int(x)] for x in tokens[1:4]]
		face = Triangle(v[0], v[2], v[1], mat)
		n = face.getNormal()
		for x in tokens[1:4]:
			for i in range(3):
				normals[int(x)][i] += n[i]
			vertex_face_num[int(x)] += 1
		face.setSmooth()
		rt.addshape(face)
		face_num -= 1
	# interpolate normals at vertices
	num = 0
	while (num < vertex_num):
		if (vertex_face_num[num] > 0):
			for i in range(3):
				normals[num][i] /= vertex_face_num[num]
		vertices[num].setNormal(tuple(normals[num]))
		num += 1
rt = Raytracer()
mat = Material(colour=(0.9, 0.9, 0.9))
LoadStanfordPlyFile(rt, mat, "../models/bunny/bun_zipper.ply", 29.0)
light = Light(position=(-5.0, 2.0, 10.0), colour=(0.9, 0.3, 0.6))
rt.addlight(light)
light2 = Light(position=(4.0, -3.0, 10.0), colour=(0.2, 0.9, 0.5))
rt.addlight(light2)
imagesize = (800, 600)
data = rt.render(imagesize)
img = Image.fromstring("RGB", imagesize, data)
img.save('bunny.png')