Merge branch 'master' into blender2.8
[blender.git] / intern / cycles / device / device_split_kernel.cpp
1 /*
2  * Copyright 2011-2016 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "device/device_split_kernel.h"
18
19 #include "kernel/kernel_types.h"
20 #include "kernel/split/kernel_split_data_types.h"
21
22 #include "util/util_logging.h"
23 #include "util/util_time.h"
24
25 CCL_NAMESPACE_BEGIN
26
27 static const double alpha = 0.1; /* alpha for rolling average */
28
29 DeviceSplitKernel::DeviceSplitKernel(Device *device)
30 : device(device),
31   split_data(device, "split_data"),
32   ray_state(device, "ray_state", MEM_READ_WRITE),
33   queue_index(device, "queue_index"),
34   use_queues_flag(device, "use_queues_flag"),
35   work_pool_wgs(device, "work_pool_wgs")
36 {
37         first_tile = true;
38
39         avg_time_per_sample = 0.0;
40
41         kernel_path_init = NULL;
42         kernel_scene_intersect = NULL;
43         kernel_lamp_emission = NULL;
44         kernel_do_volume = NULL;
45         kernel_queue_enqueue = NULL;
46         kernel_indirect_background = NULL;
47         kernel_shader_setup = NULL;
48         kernel_shader_sort = NULL;
49         kernel_shader_eval = NULL;
50         kernel_holdout_emission_blurring_pathtermination_ao = NULL;
51         kernel_subsurface_scatter = NULL;
52         kernel_direct_lighting = NULL;
53         kernel_shadow_blocked_ao = NULL;
54         kernel_shadow_blocked_dl = NULL;
55         kernel_enqueue_inactive = NULL;
56         kernel_next_iteration_setup = NULL;
57         kernel_indirect_subsurface = NULL;
58         kernel_buffer_update = NULL;
59 }
60
61 DeviceSplitKernel::~DeviceSplitKernel()
62 {
63         split_data.free();
64         ray_state.free();
65         use_queues_flag.free();
66         queue_index.free();
67         work_pool_wgs.free();
68
69         delete kernel_path_init;
70         delete kernel_scene_intersect;
71         delete kernel_lamp_emission;
72         delete kernel_do_volume;
73         delete kernel_queue_enqueue;
74         delete kernel_indirect_background;
75         delete kernel_shader_setup;
76         delete kernel_shader_sort;
77         delete kernel_shader_eval;
78         delete kernel_holdout_emission_blurring_pathtermination_ao;
79         delete kernel_subsurface_scatter;
80         delete kernel_direct_lighting;
81         delete kernel_shadow_blocked_ao;
82         delete kernel_shadow_blocked_dl;
83         delete kernel_enqueue_inactive;
84         delete kernel_next_iteration_setup;
85         delete kernel_indirect_subsurface;
86         delete kernel_buffer_update;
87 }
88
89 bool DeviceSplitKernel::load_kernels(const DeviceRequestedFeatures& requested_features)
90 {
91 #define LOAD_KERNEL(name) \
92                 kernel_##name = get_split_kernel_function(#name, requested_features); \
93                 if(!kernel_##name) { \
94                         device->set_error(string("Split kernel error: failed to load kernel_") + #name); \
95                         return false; \
96                 }
97
98         LOAD_KERNEL(path_init);
99         LOAD_KERNEL(scene_intersect);
100         LOAD_KERNEL(lamp_emission);
101         LOAD_KERNEL(do_volume);
102         LOAD_KERNEL(queue_enqueue);
103         LOAD_KERNEL(indirect_background);
104         LOAD_KERNEL(shader_setup);
105         LOAD_KERNEL(shader_sort);
106         LOAD_KERNEL(shader_eval);
107         LOAD_KERNEL(holdout_emission_blurring_pathtermination_ao);
108         LOAD_KERNEL(subsurface_scatter);
109         LOAD_KERNEL(direct_lighting);
110         LOAD_KERNEL(shadow_blocked_ao);
111         LOAD_KERNEL(shadow_blocked_dl);
112         LOAD_KERNEL(enqueue_inactive);
113         LOAD_KERNEL(next_iteration_setup);
114         LOAD_KERNEL(indirect_subsurface);
115         LOAD_KERNEL(buffer_update);
116
117 #undef LOAD_KERNEL
118
119         return true;
120 }
121
122 size_t DeviceSplitKernel::max_elements_for_max_buffer_size(device_memory& kg, device_memory& data, uint64_t max_buffer_size)
123 {
124         uint64_t size_per_element = state_buffer_size(kg, data, 1024) / 1024;
125         VLOG(1) << "Split state element size: "
126                 << string_human_readable_number(size_per_element) << " bytes. ("
127                 << string_human_readable_size(size_per_element) << ").";
128         return max_buffer_size / size_per_element;
129 }
130
131 bool DeviceSplitKernel::path_trace(DeviceTask *task,
132                                    RenderTile& tile,
133                                    device_memory& kgbuffer,
134                                    device_memory& kernel_data)
135 {
136         if(device->have_error()) {
137                 return false;
138         }
139
140         /* Get local size */
141         size_t local_size[2];
142         {
143                 int2 lsize = split_kernel_local_size();
144                 local_size[0] = lsize[0];
145                 local_size[1] = lsize[1];
146         }
147
148         /* Number of elements in the global state buffer */
149         int num_global_elements = global_size[0] * global_size[1];
150
151         /* Allocate all required global memory once. */
152         if(first_tile) {
153                 first_tile = false;
154
155                 /* Set gloabl size */
156                 {
157                         int2 gsize = split_kernel_global_size(kgbuffer, kernel_data, task);
158
159                         /* Make sure that set work size is a multiple of local
160                          * work size dimensions.
161                          */
162                         global_size[0] = round_up(gsize[0], local_size[0]);
163                         global_size[1] = round_up(gsize[1], local_size[1]);
164                 }
165
166                 num_global_elements = global_size[0] * global_size[1];
167                 assert(num_global_elements % WORK_POOL_SIZE == 0);
168
169                 /* Calculate max groups */
170
171                 /* Denotes the maximum work groups possible w.r.t. current requested tile size. */
172                 unsigned int work_pool_size = (device->info.type == DEVICE_CPU) ? WORK_POOL_SIZE_CPU : WORK_POOL_SIZE_GPU;
173                 unsigned int max_work_groups = num_global_elements / work_pool_size + 1;
174
175                 /* Allocate work_pool_wgs memory. */
176                 work_pool_wgs.alloc_to_device(max_work_groups);
177                 queue_index.alloc_to_device(NUM_QUEUES);
178                 use_queues_flag.alloc_to_device(1);
179                 split_data.alloc_to_device(state_buffer_size(kgbuffer, kernel_data, num_global_elements));
180                 ray_state.alloc(num_global_elements);
181         }
182
183 #define ENQUEUE_SPLIT_KERNEL(name, global_size, local_size) \
184                 if(device->have_error()) { \
185                         return false; \
186                 } \
187                 if(!kernel_##name->enqueue(KernelDimensions(global_size, local_size), kgbuffer, kernel_data)) { \
188                         return false; \
189                 }
190
191         tile.sample = tile.start_sample;
192
193         /* for exponential increase between tile updates */
194         int time_multiplier = 1;
195
196         while(tile.sample < tile.start_sample + tile.num_samples) {
197                 /* to keep track of how long it takes to run a number of samples */
198                 double start_time = time_dt();
199
200                 /* initial guess to start rolling average */
201                 const int initial_num_samples = 1;
202                 /* approx number of samples per second */
203                 int samples_per_second = (avg_time_per_sample > 0.0) ?
204                                          int(double(time_multiplier) / avg_time_per_sample) + 1 : initial_num_samples;
205
206                 RenderTile subtile = tile;
207                 subtile.start_sample = tile.sample;
208                 subtile.num_samples = min(samples_per_second, tile.start_sample + tile.num_samples - tile.sample);
209
210                 if(device->have_error()) {
211                         return false;
212                 }
213
214                 /* reset state memory here as global size for data_init
215                  * kernel might not be large enough to do in kernel
216                  */
217                 work_pool_wgs.zero_to_device();
218                 split_data.zero_to_device();
219                 ray_state.zero_to_device();
220
221                 if(!enqueue_split_kernel_data_init(KernelDimensions(global_size, local_size),
222                                                    subtile,
223                                                    num_global_elements,
224                                                    kgbuffer,
225                                                    kernel_data,
226                                                    split_data,
227                                                    ray_state,
228                                                    queue_index,
229                                                    use_queues_flag,
230                                                    work_pool_wgs))
231                 {
232                         return false;
233                 }
234
235                 ENQUEUE_SPLIT_KERNEL(path_init, global_size, local_size);
236
237                 bool activeRaysAvailable = true;
238                 double cancel_time = DBL_MAX;
239
240                 while(activeRaysAvailable) {
241                         /* Do path-iteration in host [Enqueue Path-iteration kernels. */
242                         for(int PathIter = 0; PathIter < 16; PathIter++) {
243                                 ENQUEUE_SPLIT_KERNEL(scene_intersect, global_size, local_size);
244                                 ENQUEUE_SPLIT_KERNEL(lamp_emission, global_size, local_size);
245                                 ENQUEUE_SPLIT_KERNEL(do_volume, global_size, local_size);
246                                 ENQUEUE_SPLIT_KERNEL(queue_enqueue, global_size, local_size);
247                                 ENQUEUE_SPLIT_KERNEL(indirect_background, global_size, local_size);
248                                 ENQUEUE_SPLIT_KERNEL(shader_setup, global_size, local_size);
249                                 ENQUEUE_SPLIT_KERNEL(shader_sort, global_size, local_size);
250                                 ENQUEUE_SPLIT_KERNEL(shader_eval, global_size, local_size);
251                                 ENQUEUE_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao, global_size, local_size);
252                                 ENQUEUE_SPLIT_KERNEL(subsurface_scatter, global_size, local_size);
253                                 ENQUEUE_SPLIT_KERNEL(queue_enqueue, global_size, local_size);
254                                 ENQUEUE_SPLIT_KERNEL(direct_lighting, global_size, local_size);
255                                 ENQUEUE_SPLIT_KERNEL(shadow_blocked_ao, global_size, local_size);
256                                 ENQUEUE_SPLIT_KERNEL(shadow_blocked_dl, global_size, local_size);
257                                 ENQUEUE_SPLIT_KERNEL(enqueue_inactive, global_size, local_size);
258                                 ENQUEUE_SPLIT_KERNEL(next_iteration_setup, global_size, local_size);
259                                 ENQUEUE_SPLIT_KERNEL(indirect_subsurface, global_size, local_size);
260                                 ENQUEUE_SPLIT_KERNEL(queue_enqueue, global_size, local_size);
261                                 ENQUEUE_SPLIT_KERNEL(buffer_update, global_size, local_size);
262
263                                 if(task->get_cancel() && cancel_time == DBL_MAX) {
264                                         /* Wait up to twice as many seconds for current samples to finish
265                                          * to avoid artifacts in render result from ending too soon.
266                                          */
267                                         cancel_time = time_dt() + 2.0 * time_multiplier;
268                                 }
269
270                                 if(time_dt() > cancel_time) {
271                                         return true;
272                                 }
273                         }
274
275                         /* Decide if we should exit path-iteration in host. */
276                         ray_state.copy_from_device(0, global_size[0] * global_size[1], 1);
277
278                         activeRaysAvailable = false;
279
280                         for(int rayStateIter = 0; rayStateIter < global_size[0] * global_size[1]; ++rayStateIter) {
281                                 if(!IS_STATE(ray_state.data(), rayStateIter, RAY_INACTIVE)) {
282                                         if(IS_STATE(ray_state.data(), rayStateIter, RAY_INVALID)) {
283                                                 /* Something went wrong, abort to avoid looping endlessly. */
284                                                 device->set_error("Split kernel error: invalid ray state");
285                                                 return false;
286                                         }
287
288                                         /* Not all rays are RAY_INACTIVE. */
289                                         activeRaysAvailable = true;
290                                         break;
291                                 }
292                         }
293
294                         if(time_dt() > cancel_time) {
295                                 return true;
296                         }
297                 }
298
299                 double time_per_sample = ((time_dt()-start_time) / subtile.num_samples);
300
301                 if(avg_time_per_sample == 0.0) {
302                         /* start rolling average */
303                         avg_time_per_sample = time_per_sample;
304                 }
305                 else {
306                         avg_time_per_sample = alpha*time_per_sample + (1.0-alpha)*avg_time_per_sample;
307                 }
308
309 #undef ENQUEUE_SPLIT_KERNEL
310
311                 tile.sample += subtile.num_samples;
312                 task->update_progress(&tile, tile.w*tile.h*subtile.num_samples);
313
314                 time_multiplier = min(time_multiplier << 1, 10);
315
316                 if(task->get_cancel()) {
317                         return true;
318                 }
319         }
320
321         return true;
322 }
323
324 CCL_NAMESPACE_END