-
Notifications
You must be signed in to change notification settings - Fork 2
/
render.py
443 lines (396 loc) · 15.3 KB
/
render.py
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import multiprocessing as mp
import numpy as np
from progress.bar import Bar
from random import random, shuffle
# Local Modules
import utils
from ray import Ray
from raytrace import raytrace
PERCENTAGE_STEP = 1
RGB_CHANNELS = 3
def avg(colors, samples):
total_sum = np.zeros(3)
for color in colors:
total_sum += color
return total_sum / samples
def create_rays(camera, height, width):
rays = []
for j in range(height):
for i in range(width):
x = i
y = height - 1 - j
# Get x projected in view coord
xp = (x / float(width)) * camera.scale_x
# Get y projected in view coord
yp = (y / float(height)) * camera.scale_y
pp = camera.p00 + xp * camera.n0 + yp * camera.n1
npe = utils.normalize(pp - camera.position)
ray = Ray(pp, npe)
rays.append(ray)
return rays
def create_rays_aa(camera, HEIGHT=100, WIDTH=100, V_SAMPLES=4, H_SAMPLES=4):
rays = []
for j in range(HEIGHT):
for i in range(WIDTH):
for n in range(V_SAMPLES):
for m in range(H_SAMPLES):
x = i + (float(m) / H_SAMPLES) + (random() / H_SAMPLES)
y = (
HEIGHT - 1 - j
+ (float(n) / V_SAMPLES)
+ (random() / V_SAMPLES)
)
# Get x projected in view coord
xp = (x / float(WIDTH)) * camera.scale_x
# Get y projected in view coord
yp = (y / float(HEIGHT)) * camera.scale_y
pp = camera.p00 + xp * camera.n0 + yp * camera.n1
npe = utils.normalize(pp - camera.position)
ray = Ray(pp, npe)
rays.append(ray)
return rays
def create_ray_aa(camera, height, width, v_samples, h_samples, pixel_pos):
"""
Create a new ray for the given camera and screen position with random
jiterring anti-aliasing sampling.
Args:
camera(Camera): Camera from where the ray is shot.
height(int): Height of the screen in pixels.
width(int): Width of the screen in pixels.
v_samples(int): Number of samples for a pixel in the vertical axis.
h_samples(int): Number of samples for a pixel in the horizontal axis.
pixel_pos(tuple): Position of a pixel sample with j, i, n, m.
Returns:
Ray: The ray for the given camera and screen position.
"""
j, i, n, m = pixel_pos
x = i + float(m) / h_samples + random() / h_samples
y = height - 1 - j + float(n) / v_samples + random() / v_samples
# Get x projected in view coord
xp = (x / width) * camera.scale_x
# Get y projected in view coord
yp = (y / height) * camera.scale_y
pp = camera.p00 + xp * camera.n0 + yp * camera.n1
npe = utils.normalize(pp - camera.position)
ray = Ray(pp, npe)
return ray
def raytrace_mp_wrapper(args):
return raytrace(*args)
def raytrace_unordered_wrapper(args):
# index refers to the scanline index of a pixel
index, height, width, v_samples, h_samples, camera, scene = args
num_samples = v_samples * h_samples
color = np.zeros(RGB_CHANNELS)
for n in range(v_samples):
for m in range(h_samples):
i = index % width
j = index // width
pixel_sample_pos = j, i, n, m
ray = create_ray_aa(
camera, height, width, v_samples, h_samples, pixel_sample_pos
)
sample_color = raytrace(ray, scene)
color += sample_color / num_samples
color = color.round().astype(np.uint8)
return (index, color)
def render(scene, camera, HEIGHT=100, WIDTH=100):
"""
Render the image for the given scene and camera using raytracing.
Args:
scene(Scene): The scene that contains objects, cameras and lights.
camera(Camera): The camera that is rendering this image.
Returns:
numpy.array: The pixels with the raytraced colors.
"""
output = np.zeros((HEIGHT, WIDTH, RGB_CHANNELS), dtype=np.uint8)
if not scene or scene.is_empty() or not camera or camera.inside(
scene.objects
):
print("Cannot generate an image")
return output
iterations = HEIGHT * WIDTH
bar = Bar(
'Raytracing',
max=iterations,
suffix='%(percent)d%% [%(elapsed_td)s / %(eta_td)s]',
check_tty=False
)
for j in range(HEIGHT):
for i in range(WIDTH):
x = i
y = HEIGHT - 1 - j
# Get x projected in view coord
xp = (x / float(WIDTH)) * camera.scale_x
# Get y projected in view coord
yp = (y / float(HEIGHT)) * camera.scale_y
pp = camera.p00 + xp * camera.n0 + yp * camera.n1
npe = utils.normalize(pp - camera.position)
ray = Ray(pp, npe)
color = raytrace(ray, scene)
output[j][i] = color.round().astype(np.uint8)
bar.next()
bar.finish()
return output
def render_aa(scene, camera, HEIGHT=100, WIDTH=100, V_SAMPLES=4, H_SAMPLES=4):
"""
Render the image for the given scene and camera using raytracing.
Args:
scene(Scene): The scene that contains objects, cameras and lights.
camera(Camera): The camera that is rendering this image.
Returns:
numpy.array: The pixels with the raytraced colors.
"""
output = np.zeros((HEIGHT, WIDTH, RGB_CHANNELS), dtype=np.uint8)
if not scene or scene.is_empty() or not camera or camera.inside(
scene.objects
):
print("Cannot generate an image")
return output
total_samples = H_SAMPLES * V_SAMPLES
# This is for showing progress %
iterations = HEIGHT * WIDTH * total_samples
bar = Bar(
'Raytracing',
max=iterations,
suffix='%(percent)d%% [%(elapsed_td)s / %(eta_td)s]',
check_tty=False
)
for j in range(HEIGHT):
for i in range(WIDTH):
color = np.array([0, 0, 0], dtype=float)
for n in range(V_SAMPLES):
for m in range(H_SAMPLES):
r0, r1 = np.random.random_sample(2)
# Floats x, y inside the image plane grid
x = i + ((float(m) + r0) / H_SAMPLES)
y = HEIGHT - 1 - j + ((float(n) + r1) / V_SAMPLES)
# Get x projected in view coord
xp = (x / float(WIDTH)) * camera.scale_x
# Get y projected in view coord
yp = (y / float(HEIGHT)) * camera.scale_y
pp = camera.p00 + xp * camera.n0 + yp * camera.n1
npe = utils.normalize(pp - camera.position)
ray = Ray(pp, npe)
color += raytrace(ray, scene) / float(total_samples)
bar.next()
output[j][i] = color.round().astype(np.uint8)
bar.finish()
return output
def render_mp(scene, camera, height, width):
"""
Render the image for the given scene and camera using raytracing in multi-
processors.
Args:
scene(Scene): The scene that contains objects, cameras and lights.
camera(Camera): The camera that is rendering this image.
Returns:
numpy.array: The pixels with the raytraced colors.
"""
output = np.zeros((height, width, RGB_CHANNELS), dtype=np.uint8)
if not scene or scene.is_empty() or not camera or camera.inside(
scene.objects
):
print("Cannot generate an image")
return output
print("Creating rays...")
rays = create_rays(camera, height, width)
pool = mp.Pool(mp.cpu_count())
print("Shooting rays...")
ray_colors = pool.map(
raytrace_mp_wrapper, [(ray, scene) for ray in rays]
)
pool.close()
print("Arranging pixels...")
for j in range(height):
for i in range(width):
output[j][i] = ray_colors[i + j * width]
return output
def render_aa_mp(
scene, camera, HEIGHT=100, WIDTH=100, V_SAMPLES=4, H_SAMPLES=4
):
"""
Render the image for the given scene and camera using raytracing in multi-
processors.
Args:
scene(Scene): The scene that contains objects, cameras and lights.
camera(Camera): The camera that is rendering this image.
Returns:
numpy.array: The pixels with the raytraced colors.
"""
output = np.zeros((HEIGHT, WIDTH, RGB_CHANNELS), dtype=np.uint8)
if not scene or scene.is_empty() or not camera or camera.inside(
scene.objects
):
print("Cannot generate an image")
return output
print("Creating rays...")
rays = create_rays_aa(camera, HEIGHT, WIDTH, V_SAMPLES, H_SAMPLES)
pool = mp.Pool(mp.cpu_count())
print("Shooting rays...")
ray_colors = pool.map(
raytrace_mp_wrapper, [(ray, scene) for ray in rays]
)
pool.close()
print("Arranging pixels...")
samples = H_SAMPLES * V_SAMPLES
# using list comprehension
pixel_colors = [
avg(ray_colors[i:i + samples], samples)
for i in range(0, len(ray_colors), samples)
]
n = WIDTH * HEIGHT
pixels_2d = [pixel_colors[i:i + WIDTH] for i in range(0, n, WIDTH)]
output = np.asarray(pixels_2d).round().astype(np.uint8)
return output
def render_aa_mp_unordered(
scene, camera, HEIGHT=100, WIDTH=100, V_SAMPLES=4, H_SAMPLES=4
):
"""
Render the image for the given scene and camera using raytracing in multi-
processors unordered with random-jittering anti-aliasing.
Args:
scene(Scene): The scene that contains objects, cameras and lights.
camera(Camera): The camera that is rendering this image.
Returns:
numpy.array: The pixels with the raytraced colors.
"""
output = np.zeros([HEIGHT, WIDTH, RGB_CHANNELS], dtype=np.uint8)
n = HEIGHT * WIDTH
if not scene or scene.is_empty() or not camera or camera.inside(
scene.objects
):
print("Cannot generate an image")
return output
threads_count = mp.cpu_count()
pool = mp.Pool(threads_count)
ray_colors = pool.imap_unordered(
raytrace_unordered_wrapper,
[
(
index, HEIGHT, WIDTH, V_SAMPLES, H_SAMPLES, camera, scene
) for index in range(n)
],
chunksize=n//threads_count
)
pool.close()
print("Shooting rays...")
for index, color in ray_colors:
i = index % WIDTH
j = index // WIDTH
output[j][i] = color
return output
def render_dof(scene, camera, HEIGHT=100, WIDTH=100, V_SAMPLES=6, H_SAMPLES=6):
"""
Render the image for the given scene and camera using raytracing with
depth of field.
Args:
scene(Scene): The scene that contains objects, cameras and lights.
camera(Camera): The camera that is rendering this image.
Returns:
numpy.array: The pixels with the raytraced colors.
"""
output = np.zeros((HEIGHT, WIDTH, RGB_CHANNELS), dtype=np.uint8)
if not scene or scene.is_empty() or not camera or camera.inside(
scene.objects
):
print("Cannot generate an image")
return output
total_samples = H_SAMPLES * V_SAMPLES
iterations = HEIGHT * WIDTH * total_samples
bar = Bar(
'Raytracing',
max=iterations,
suffix='%(percent)d%% [%(elapsed_td)s / %(eta_td)s]',
check_tty=False
)
for j in range(HEIGHT):
for i in range(WIDTH):
color = np.array([0, 0, 0], dtype=float)
lens_sample_offsets = []
n0 = camera.n0
n1 = camera.n1
# Generate random offsets inside the camera aperture
for n in range(V_SAMPLES):
for m in range(H_SAMPLES):
ap = camera.lens_params.ap
# Use random samples from a unit circle
r0, r1 = np.random.random_sample(2)
while r0 ** 2 + r1 ** 2 > 1:
# repeat until you get a sample that is inside a circle
# of radius 1
r0, r1 = np.random.random_sample(2)
x_offset = ((r0 - 0.5) * m) / H_SAMPLES * ap
y_offset = ((r1 - 0.5) * n) / V_SAMPLES * ap
lens_sample_offsets.append((x_offset, y_offset))
shuffle(lens_sample_offsets)
# Shoot rays for sub-samples
for n in range(V_SAMPLES):
for m in range(H_SAMPLES):
r0, r1 = np.random.random_sample(2)
x = i + ((float(m) + r0) / H_SAMPLES)
y = HEIGHT - 1 - j + ((float(n) + r1) / V_SAMPLES)
# Get x projected in view coord
xp = (x / float(WIDTH)) * camera.scale_x
# Get y projected in view coord
yp = (y / float(HEIGHT)) * camera.scale_y
pp = camera.p00 + xp * camera.n0 + yp * camera.n1
npe = utils.normalize(pp - camera.position)
# Randomly offset ray
x_offset, y_offset = lens_sample_offsets.pop()
ps = pp + x_offset * n0 + y_offset * n1
fp = pp + npe * camera.lens_params.f
director = utils.normalize(fp - ps)
ray = Ray(ps, director)
color += raytrace(ray, scene) / float(total_samples)
bar.next()
output[j][i] = color.round().astype(np.uint8)
bar.finish()
return output
def render_aa_t(
scene, camera, func, HEIGHT=100, WIDTH=100, V_SAMPLES=4,
H_SAMPLES=4
):
"""
Render the image for the given scene and camera using a template function.
Args:
scene(Scene): The scene that contains objects, cameras and lights.
camera(Camera): The camera that is rendering this image.
Returns:
numpy.array: The pixels with the raytraced colors.
"""
output = np.zeros((HEIGHT, WIDTH, RGB_CHANNELS), dtype=np.uint8)
if not scene or scene.is_empty() or not camera or camera.inside(
scene.objects
):
print("Cannot generate an image")
return output
total_samples = H_SAMPLES * V_SAMPLES
# This is for showing progress %
iterations = HEIGHT * WIDTH
bar = Bar(
'Raytracing',
max=iterations,
suffix='%(percent)d%% [%(elapsed_td)s / %(eta_td)s]',
check_tty=False
)
for j in range(HEIGHT):
for i in range(WIDTH):
color = np.array([0, 0, 0], dtype=float)
for n in range(V_SAMPLES):
for m in range(H_SAMPLES):
r0, r1 = np.random.random_sample(2)
# Floats x, y inside the image plane grid
x = i + ((float(m) + r0) / H_SAMPLES)
y = HEIGHT - 1 - j + ((float(n) + r1) / V_SAMPLES)
# Get x projected in view coord
xp = (x / float(WIDTH)) * camera.scale_x
# Get y projected in view coord
yp = (y / float(HEIGHT)) * camera.scale_y
pp = camera.p00 + xp * camera.n0 + yp * camera.n1
npe = utils.normalize(pp - camera.position)
ray = Ray(pp, npe)
color += func(ray, scene) / float(total_samples)
bar.next()
output[j][i] = color.round().astype(np.uint8)
bar.finish()
return output