5 |
5 |
6 import sys |
6 import sys |
7 sys.path.append(open('ModulePath').read().strip()) |
7 sys.path.append(open('ModulePath').read().strip()) |
8 |
8 |
9 from raytracer import Raytracer, Light, Sphere, Triangle, NormalVertex, Material |
9 from raytracer import Raytracer, Light, Sphere, Triangle, NormalVertex, Material |
|
10 from plyreader import LoadStanfordPlyFile |
10 import Image |
11 import Image |
11 |
|
12 def LoadStanfordPlyFile(rt, mat, filename, scale): |
|
13 vertices = [] |
|
14 normals = [] |
|
15 vertex_face_num = [] |
|
16 fp = file(filename) |
|
17 # read header |
|
18 tokens = (0,) |
|
19 while (tokens[0] != "end_header"): |
|
20 tokens = fp.readline().split() |
|
21 if (tokens[0] == "element"): |
|
22 if (tokens[1] == "vertex"): |
|
23 vertex_num = int(tokens[2]) |
|
24 if (tokens[1] == "face"): |
|
25 face_num = int(tokens[2]) |
|
26 |
|
27 # read vertices |
|
28 num = vertex_num |
|
29 while (num): |
|
30 tokens = fp.readline().split() |
|
31 v = [scale*float(x) for x in tokens[0:3]] |
|
32 v[0] = -v[0]-1 |
|
33 v[1] = v[1]-3 |
|
34 vertices.append(NormalVertex(tuple(v))) |
|
35 normals.append([0.,0.,0.]) |
|
36 vertex_face_num.append(0) |
|
37 num -= 1 |
|
38 |
|
39 # read faces |
|
40 while (face_num): |
|
41 tokens = fp.readline().split() |
|
42 if (tokens[0] != "3"): |
|
43 print "ply warning: faces of %d vertices not supported" % tokens[0] |
|
44 v = [vertices[int(x)] for x in tokens[1:4]] |
|
45 face = Triangle(v[0], v[2], v[1], mat) |
|
46 n = face.getNormal() |
|
47 for x in tokens[1:4]: |
|
48 for i in range(3): |
|
49 normals[int(x)][i] += n[i] |
|
50 vertex_face_num[int(x)] += 1 |
|
51 face.setSmooth() |
|
52 rt.addshape(face) |
|
53 face_num -= 1 |
|
54 |
|
55 # interpolate normals at vertices |
|
56 num = 0 |
|
57 while (num < vertex_num): |
|
58 if (vertex_face_num[num] > 0): |
|
59 for i in range(3): |
|
60 normals[num][i] /= vertex_face_num[num] |
|
61 vertices[num].setNormal(tuple(normals[num])) |
|
62 num += 1 |
|
63 |
12 |
64 rt = Raytracer() |
13 rt = Raytracer() |
65 mat = Material(colour=(0.9, 0.9, 0.9)) |
14 mat = Material(colour=(0.9, 0.9, 0.9)) |
66 LoadStanfordPlyFile(rt, mat, "../models/bunny/bun_zipper.ply", 29.0) |
15 LoadStanfordPlyFile(rt, "../models/bunny/bun_zipper.ply", |
|
16 mat, smooth=True, scale=(-29.0, 29.0, 29.0), trans=(-1,-3,-3)) |
67 |
17 |
68 light = Light(position=(-5.0, 2.0, 10.0), colour=(0.9, 0.3, 0.6)) |
18 light = Light(position=(-5.0, 2.0, 10.0), colour=(0.9, 0.3, 0.6)) |
69 rt.addlight(light) |
19 rt.addlight(light) |
70 |
20 |
71 light2 = Light(position=(4.0, -3.0, 10.0), colour=(0.2, 0.9, 0.5)) |
21 light2 = Light(position=(4.0, -3.0, 10.0), colour=(0.2, 0.9, 0.5)) |