1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
|
#!/usr/bin/env python
import os
import sys
import time
import numpy as np
import inspect
import pygame
from pygame.locals import *
import src
from camera import get_rays
from geometry import Mesh, Solid, Geometry
from transform import rotate
from optics import *
from gpu import *
#from pycuda import autoinit
from pycuda.compiler import SourceModule
from pycuda import gpuarray
import pycuda.driver as cuda
def buildable(identifier):
"""
Create a decorator which tags a function as buildable and assigns the
identifying string `identifier`.
Example:
>>> @buildable('my_sphere')
>>> def build_my_sphere():
>>> g = Geometry()
>>> g.add_solid(Solid(sphere(), vacuum, water))
>>> return g
"""
def tag_as_buildable(func):
func.buildable = True
func.identifier = identifier
return func
return tag_as_buildable
def screenshot(screen, name='', dir='', index=0):
"""Take a screenshot of `screen`."""
if name == '':
root, ext = 'screenshot', 'png'
else:
root, ext = name, 'png'
i = index
filename = os.path.join(dir,'.'.join([root + str(i).zfill(4), ext]))
while os.path.exists(filename):
filename = os.path.join(dir,'.'.join([root + str(i).zfill(4), ext]))
i += 1
pygame.image.save(screen, filename)
print 'image saved to %s' % filename
def build(obj, bits):
"""Construct and build a geometry from `obj`."""
if inspect.isfunction(obj):
try:
if obj.buildable:
obj = obj()
except AttributeError:
raise Exception('function %s is not buildable.' % obj.__name__)
if isinstance(obj, Geometry):
geometry = obj
elif isinstance(obj, Solid):
geometry = Geometry()
geometry.add_solid(obj)
elif isinstance(obj, Mesh):
geometry = Geometry()
geometry.add_solid(Solid(obj, vacuum, vacuum, surface=lambertian_surface, color=0x99ffffff))
else:
raise Exception('cannot build type %s' % type(obj))
geometry.build(bits)
return geometry
def box(lower_bound, upper_bound):
"""
Return a mesh of the box defined by the opposing corners `lower_bound`
and `upper_bound`.
"""
dx, dy, dz = upper_bound - lower_bound
vertices = np.array([lower_bound,
lower_bound + (dx,0,0),
lower_bound + (dx,dy,0),
lower_bound + (0,dy,0),
lower_bound + (0,0,dz),
lower_bound + (dx,0,dz),
lower_bound + (dx,dy,dz),
lower_bound + (0,dy,dz)])
triangles = np.empty((12,3), dtype=np.int32)
# bottom
triangles[0] = (1,3,2)
triangles[1] = (1,4,3)
# top
triangles[2] = (5,7,6)
triangles[3] = (5,8,7)
# left
triangles[4] = (5,1,2)
triangles[5] = (5,2,6)
# right
triangles[6] = (3,4,8)
triangles[7] = (3,8,7)
# front
triangles[8] = (2,3,7)
triangles[9] = (2,7,6)
# back
triangles[10] = (1,5,8)
triangles[11] = (1,8,4)
triangles -= 1
return Mesh(vertices, triangles)
def bvh_mesh(geometry, layer):
lower_bounds = geometry.lower_bounds[geometry.layers == layer]
upper_bounds = geometry.upper_bounds[geometry.layers == layer]
if len(lower_bounds) == 0 or len(upper_bounds) == 0:
raise Exception('no nodes at layer %i' % layer)
mesh = box(lower_bounds[0], upper_bounds[0])
for lower_bound, upper_bound in zip(lower_bounds, upper_bounds)[1:]:
mesh += box(lower_bound, upper_bound)
return mesh
def view(viewable, size=(800,600), name='', bits=8, load_bvh=False):
"""
Render `viewable` in a pygame window.
Movement:
- zoom: scroll the mouse wheel
- rotate: click and drag the mouse
- move: shift+click and drag the mouse
"""
gpu = GPU()
geometry = build(viewable, bits)
if load_bvh:
print 'loading bvh...'
bvhg = []
bvhg.append(geometry)
for layer in sorted(np.unique(geometry.layers)):
print 'building layer %i' % layer
bvhg.append(build(bvh_mesh(geometry, layer), bits))
lower_bound, upper_bound = geometry.mesh.get_bounds()
scale = np.linalg.norm(upper_bound-lower_bound)
#from pycuda import autoinit
#print 'device %s' % autoinit.device.name()
module = gpu.module
#module = SourceModule(src.kernel, options=['-I' + src.dir], no_extern_c=True)#, cache_dir=False)
#geometry.load(module)
gpu.load_geometry(geometry)
cuda_raytrace = module.get_function('ray_trace')
cuda_rotate = module.get_function('rotate')
cuda_translate = module.get_function('translate')
pygame.init()
width, height = size
screen = pygame.display.set_mode(size)
pygame.display.set_caption(name)
#camera = Camera(size)
diagonal = np.linalg.norm(upper_bound-lower_bound)
point = np.array([0, diagonal*1.75, (lower_bound[2]+upper_bound[2])/2])
axis1 = np.array([1,0,0], dtype=np.double)
axis2 = np.array([0,0,1], dtype=np.double)
#camera.position(point)
origins, directions = get_rays(point, size)
origins_gpu = gpuarray.to_gpu(origins.astype(np.float32).view(gpuarray.vec.float3))
directions_gpu = gpuarray.to_gpu(directions.astype(np.float32).view(gpuarray.vec.float3))
pixels_gpu = gpuarray.zeros(width*height, dtype=np.int32)
nblocks = 64
def update():
"""Render the mesh and display to screen."""
t0 = time.time()
cuda_raytrace(np.int32(pixels_gpu.size), origins_gpu, directions_gpu, pixels_gpu, block=(nblocks,1,1), grid=(pixels_gpu.size//nblocks+1,1))
cuda.Context.synchronize()
elapsed = time.time() - t0
print 'elapsed %f sec' % elapsed
pygame.surfarray.blit_array(screen, pixels_gpu.get().reshape(size))
pygame.display.flip()
update()
done = False
clicked = False
shift = False
current_layer = 0
while not done:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
if event.button == 4:
v = scale*np.cross(axis1,axis2)/10.0
cuda_translate(np.int32(pixels_gpu.size), origins_gpu, gpuarray.vec.make_float3(*v), block=(nblocks,1,1), grid=(pixels_gpu.size//nblocks+1,1))
point += v
update()
if event.button == 5:
v = -scale*np.cross(axis1,axis2)/10.0
cuda_translate(np.int32(pixels_gpu.size), origins_gpu, gpuarray.vec.make_float3(*v), block=(nblocks,1,1), grid=(pixels_gpu.size//nblocks+1,1))
point += v
update()
if event.button == 1:
clicked = True
mouse_position = pygame.mouse.get_rel()
if event.type == MOUSEBUTTONUP:
if event.button == 1:
clicked = False
if event.type == MOUSEMOTION and clicked:
movement = np.array(pygame.mouse.get_rel())
if (movement == 0).all():
continue
length = np.linalg.norm(movement)
mouse_direction = movement[0]*axis1 + movement[1]*axis2
mouse_direction /= np.linalg.norm(mouse_direction)
if shift:
v = mouse_direction*scale*length/float(width)
cuda_translate(np.int32(pixels_gpu.size), origins_gpu, gpuarray.vec.make_float3(*v), block=(nblocks,1,1), grid=(pixels_gpu.size//nblocks+1,1))
point += v
update()
else:
phi = np.float32(2*np.pi*length/float(width))
n = rotate(mouse_direction, np.pi/2, \
-np.cross(axis1,axis2))
cuda_rotate(np.int32(pixels_gpu.size), origins_gpu, phi, gpuarray.vec.make_float3(*n), block=(nblocks,1,1), grid=(pixels_gpu.size//nblocks+1,1))
cuda_rotate(np.int32(pixels_gpu.size), directions_gpu, phi, gpuarray.vec.make_float3(*n), block=(nblocks,1,1), grid=(pixels_gpu.size//nblocks+1,1))
point = rotate(point, phi, n)
axis1 = rotate(axis1, phi, n)
axis2 = rotate(axis2, phi, n)
update()
if event.type == KEYDOWN:
if event.key == K_LSHIFT or event.key == K_RSHIFT:
shift = True
if event.key == K_ESCAPE:
done = True
break
if event.key == K_PAGEUP and load_bvh:
try:
if current_layer+1 >= len(bvhg):
raise IndexError
geometry = bvhg[current_layer+1]
current_layer += 1
gpu.load_geometry(geometry)
#geometry.load(module, color=True)
update()
except IndexError:
print 'no further layers to view'
if event.key == K_PAGEDOWN and load_bvh:
try:
if current_layer-1 < 0:
raise IndexError
geometry = bvhg[current_layer-1]
current_layer -= 1
gpu.load_geometry(geometry)
#geometry.load(module, color=True)
update()
except IndexError:
print 'no further layers to view'
if event.key == K_F12:
screenshot(screen, name)
if event.type == KEYUP:
if event.key == K_LSHIFT or event.key == K_RSHIFT:
shift = False
if event.type == pygame.QUIT:
done = True
break
pygame.display.quit()
if __name__ == '__main__':
import optparse
from stl import mesh_from_stl
import solids
import detectors
import scenes
parser = optparse.OptionParser('%prog filename.stl')
parser.add_option('-b', '--bits', type='int', dest='bits',
help='bits for z-ordering space axes', default=8)
parser.add_option('-l', action='store_true', dest='load_bvh',
help='load bounding volumes', default=False)
parser.add_option('-r', '--resolution', dest='resolution',
help='specify resolution', default='800,600')
options, args = parser.parse_args()
if len(args) < 1:
sys.exit(parser.format_help())
size = [int(s) for s in options.resolution.split(',')]
if os.path.exists(args[0]):
head, tail = os.path.split(args[0])
root, ext = os.path.splitext(tail)
if ext.lower() in ('.stl', '.bz2'):
view(mesh_from_stl(args[0]), size, root, options.bits, options.load_bvh)
else:
members = dict(inspect.getmembers(detectors) + inspect.getmembers(solids) + inspect.getmembers(scenes))
buildable_lookup = {}
for member in members.values():
if inspect.isfunction(member) and \
hasattr(member, 'buildable') and member.buildable == True:
buildable_lookup[member.identifier] = member
if args[0] in buildable_lookup:
view(buildable_lookup[args[0]], size, args[0], options.bits, options.load_bvh)
else:
sys.exit("couldn't find object %s" % args[0])
|