demos/plyreader.py
branchpyrit
changeset 29 574c34441a1c
child 41 c1080cb5bd6d
equal deleted inserted replaced
28:ffe83ca074f3 29:574c34441a1c
       
     1 from raytracer import Triangle, NormalVertex
       
     2 
       
     3 def LoadStanfordPlyFile(rt, filename, mat, smooth, scale=(1,1,1), trans=(0,0,0)):
       
     4 	if (type(scale) == float or type(scale) == int):
       
     5 		scale = (scale,)*3
       
     6 	vertices = []
       
     7 	normals = []
       
     8 	vertex_face_num = []
       
     9 	fp = file(filename)
       
    10 	# read header
       
    11 	tokens = (0,)
       
    12 	while (tokens[0] != "end_header"):
       
    13 		tokens = fp.readline().split()
       
    14 		if (tokens[0] == "element"):
       
    15 			if (tokens[1] == "vertex"):
       
    16 				vertex_num = int(tokens[2])
       
    17 			if (tokens[1] == "face"):
       
    18 				face_num = int(tokens[2])
       
    19 
       
    20 	# read vertices
       
    21 	num = vertex_num
       
    22 	while (num):
       
    23 		tokens = fp.readline().split()
       
    24 		v = [float(x) for x in tokens[0:3]]
       
    25 		v[0] = scale[0]*v[0] + trans[0]
       
    26 		v[1] = scale[1]*v[1] + trans[1]
       
    27 		v[2] = scale[2]*v[2] + trans[2]
       
    28 		vertices.append(NormalVertex(tuple(v)))
       
    29 		normals.append([0.,0.,0.])
       
    30 		vertex_face_num.append(0)
       
    31 		num -= 1
       
    32 
       
    33 	# read faces
       
    34 	while (face_num):
       
    35 		tokens = fp.readline().split()
       
    36 		if (tokens[0] != "3"):
       
    37 			print "ply warning: faces of %d vertices not supported" % tokens[0]
       
    38 		v = [vertices[int(x)] for x in tokens[1:4]]
       
    39 		face = Triangle(v[0], v[2], v[1], mat)
       
    40 		n = face.getNormal()
       
    41 		for x in tokens[1:4]:
       
    42 			for i in range(3):
       
    43 				normals[int(x)][i] += n[i]
       
    44 			vertex_face_num[int(x)] += 1
       
    45 		if (smooth):
       
    46 			face.setSmooth()
       
    47 		rt.addshape(face)
       
    48 		face_num -= 1
       
    49 
       
    50 	# interpolate normals at vertices
       
    51 	num = 0
       
    52 	while (num < vertex_num):
       
    53 		if (vertex_face_num[num] > 0):
       
    54 			for i in range(3):
       
    55 				normals[num][i] /= vertex_face_num[num]
       
    56 		vertices[num].setNormal(tuple(normals[num]))
       
    57 		num += 1