author | Radek Brich <radek.brich@devl.cz> |
Fri, 11 Apr 2008 12:46:36 +0200 | |
branch | pyrit |
changeset 67 | 249553e1d4fe |
parent 41 | c1080cb5bd6d |
child 69 | 303583d2fb97 |
permissions | -rw-r--r-- |
41
c1080cb5bd6d
fix possible division by zero in ccdemos/common_ply.h
Radek Brich <radek.brich@devl.cz>
parents:
29
diff
changeset
|
1 |
# Stanford .ply file loader |
c1080cb5bd6d
fix possible division by zero in ccdemos/common_ply.h
Radek Brich <radek.brich@devl.cz>
parents:
29
diff
changeset
|
2 |
|
29 | 3 |
from raytracer import Triangle, NormalVertex |
4 |
||
5 |
def LoadStanfordPlyFile(rt, filename, mat, smooth, scale=(1,1,1), trans=(0,0,0)): |
|
6 |
if (type(scale) == float or type(scale) == int): |
|
7 |
scale = (scale,)*3 |
|
8 |
vertices = [] |
|
9 |
normals = [] |
|
10 |
vertex_face_num = [] |
|
11 |
fp = file(filename) |
|
12 |
# read header |
|
13 |
tokens = (0,) |
|
14 |
while (tokens[0] != "end_header"): |
|
15 |
tokens = fp.readline().split() |
|
16 |
if (tokens[0] == "element"): |
|
17 |
if (tokens[1] == "vertex"): |
|
18 |
vertex_num = int(tokens[2]) |
|
19 |
if (tokens[1] == "face"): |
|
20 |
face_num = int(tokens[2]) |
|
21 |
||
22 |
# read vertices |
|
23 |
num = vertex_num |
|
24 |
while (num): |
|
25 |
tokens = fp.readline().split() |
|
26 |
v = [float(x) for x in tokens[0:3]] |
|
27 |
v[0] = scale[0]*v[0] + trans[0] |
|
28 |
v[1] = scale[1]*v[1] + trans[1] |
|
29 |
v[2] = scale[2]*v[2] + trans[2] |
|
30 |
vertices.append(NormalVertex(tuple(v))) |
|
31 |
normals.append([0.,0.,0.]) |
|
32 |
vertex_face_num.append(0) |
|
33 |
num -= 1 |
|
34 |
||
35 |
# read faces |
|
36 |
while (face_num): |
|
37 |
tokens = fp.readline().split() |
|
38 |
if (tokens[0] != "3"): |
|
39 |
print "ply warning: faces of %d vertices not supported" % tokens[0] |
|
40 |
v = [vertices[int(x)] for x in tokens[1:4]] |
|
41 |
face = Triangle(v[0], v[2], v[1], mat) |
|
42 |
n = face.getNormal() |
|
43 |
for x in tokens[1:4]: |
|
44 |
for i in range(3): |
|
45 |
normals[int(x)][i] += n[i] |
|
46 |
vertex_face_num[int(x)] += 1 |
|
47 |
if (smooth): |
|
48 |
face.setSmooth() |
|
49 |
rt.addshape(face) |
|
50 |
face_num -= 1 |
|
51 |
||
52 |
# interpolate normals at vertices |
|
53 |
num = 0 |
|
54 |
while (num < vertex_num): |
|
55 |
if (vertex_face_num[num] > 0): |
|
56 |
for i in range(3): |
|
57 |
normals[num][i] /= vertex_face_num[num] |
|
58 |
vertices[num].setNormal(tuple(normals[num])) |
|
59 |
num += 1 |