Merge branch 'master' into blender2.8
[blender.git] / intern / cycles / device / device_cpu.cpp
1 /*
2  * Copyright 2011-2013 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 <stdlib.h>
18 #include <string.h>
19
20 /* So ImathMath is included before our kernel_cpu_compat. */
21 #ifdef WITH_OSL
22 /* So no context pollution happens from indirectly included windows.h */
23 #  include "util/util_windows.h"
24 #  include <OSL/oslexec.h>
25 #endif
26
27 #include "device/device.h"
28 #include "device/device_denoising.h"
29 #include "device/device_intern.h"
30 #include "device/device_split_kernel.h"
31
32 #include "kernel/kernel.h"
33 #include "kernel/kernel_compat_cpu.h"
34 #include "kernel/kernel_types.h"
35 #include "kernel/split/kernel_split_data.h"
36 #include "kernel/kernel_globals.h"
37
38 #include "kernel/filter/filter.h"
39
40 #include "kernel/osl/osl_shader.h"
41 #include "kernel/osl/osl_globals.h"
42
43 #include "render/buffers.h"
44
45 #include "util/util_debug.h"
46 #include "util/util_foreach.h"
47 #include "util/util_function.h"
48 #include "util/util_logging.h"
49 #include "util/util_map.h"
50 #include "util/util_opengl.h"
51 #include "util/util_progress.h"
52 #include "util/util_system.h"
53 #include "util/util_thread.h"
54
55 CCL_NAMESPACE_BEGIN
56
57 class CPUDevice;
58
59 /* Has to be outside of the class to be shared across template instantiations. */
60 static const char *logged_architecture = "";
61
62 template<typename F>
63 class KernelFunctions {
64 public:
65         KernelFunctions()
66         {
67                 kernel = (F)NULL;
68         }
69
70         KernelFunctions(F kernel_default,
71                         F kernel_sse2,
72                         F kernel_sse3,
73                         F kernel_sse41,
74                         F kernel_avx,
75                         F kernel_avx2)
76         {
77                 const char *architecture_name = "default";
78                 kernel = kernel_default;
79
80                 /* Silence potential warnings about unused variables
81                  * when compiling without some architectures. */
82                 (void)kernel_sse2;
83                 (void)kernel_sse3;
84                 (void)kernel_sse41;
85                 (void)kernel_avx;
86                 (void)kernel_avx2;
87 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_AVX2
88                 if(system_cpu_support_avx2()) {
89                         architecture_name = "AVX2";
90                         kernel = kernel_avx2;
91                 }
92                 else
93 #endif
94 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_AVX
95                 if(system_cpu_support_avx()) {
96                         architecture_name = "AVX";
97                         kernel = kernel_avx;
98                 }
99                 else
100 #endif
101 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE41
102                 if(system_cpu_support_sse41()) {
103                         architecture_name = "SSE4.1";
104                         kernel = kernel_sse41;
105                 }
106                 else
107 #endif
108 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE3
109                 if(system_cpu_support_sse3()) {
110                         architecture_name = "SSE3";
111                         kernel = kernel_sse3;
112                 }
113                 else
114 #endif
115 #ifdef WITH_CYCLES_OPTIMIZED_KERNEL_SSE2
116                 if(system_cpu_support_sse2()) {
117                         architecture_name = "SSE2";
118                         kernel = kernel_sse2;
119                 }
120 #endif
121
122                 if(strstr(architecture_name, logged_architecture) != 0) {
123                         VLOG(1) << "Will be using " << architecture_name << " kernels.";
124                         logged_architecture = architecture_name;
125                 }
126         }
127
128         inline F operator()() const {
129                 assert(kernel);
130                 return kernel;
131         }
132 protected:
133         F kernel;
134 };
135
136 class CPUSplitKernel : public DeviceSplitKernel {
137         CPUDevice *device;
138 public:
139         explicit CPUSplitKernel(CPUDevice *device);
140
141         virtual bool enqueue_split_kernel_data_init(const KernelDimensions& dim,
142                                                     RenderTile& rtile,
143                                                     int num_global_elements,
144                                                     device_memory& kernel_globals,
145                                                     device_memory& kernel_data_,
146                                                     device_memory& split_data,
147                                                     device_memory& ray_state,
148                                                     device_memory& queue_index,
149                                                     device_memory& use_queues_flag,
150                                                     device_memory& work_pool_wgs);
151
152         virtual SplitKernelFunction* get_split_kernel_function(string kernel_name, const DeviceRequestedFeatures&);
153         virtual int2 split_kernel_local_size();
154         virtual int2 split_kernel_global_size(device_memory& kg, device_memory& data, DeviceTask *task);
155         virtual uint64_t state_buffer_size(device_memory& kg, device_memory& data, size_t num_threads);
156 };
157
158 class CPUDevice : public Device
159 {
160 public:
161         TaskPool task_pool;
162         KernelGlobals kernel_globals;
163
164 #ifdef WITH_OSL
165         OSLGlobals osl_globals;
166 #endif
167
168         bool use_split_kernel;
169
170         DeviceRequestedFeatures requested_features;
171
172         KernelFunctions<void(*)(KernelGlobals *, float *, unsigned int *, int, int, int, int, int)>   path_trace_kernel;
173         KernelFunctions<void(*)(KernelGlobals *, uchar4 *, float *, float, int, int, int, int)>       convert_to_half_float_kernel;
174         KernelFunctions<void(*)(KernelGlobals *, uchar4 *, float *, float, int, int, int, int)>       convert_to_byte_kernel;
175         KernelFunctions<void(*)(KernelGlobals *, uint4 *, float4 *, float*, int, int, int, int, int)> shader_kernel;
176
177         KernelFunctions<void(*)(int, TilesInfo*, int, int, float*, float*, float*, float*, float*, int*, int, int, bool)> filter_divide_shadow_kernel;
178         KernelFunctions<void(*)(int, TilesInfo*, int, int, int, int, float*, float*, int*, int, int, bool)>               filter_get_feature_kernel;
179         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int)>                                     filter_detect_outliers_kernel;
180         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int)>                                     filter_combine_halves_kernel;
181
182         KernelFunctions<void(*)(int, int, float*, float*, float*, int*, int, int, float, float)> filter_nlm_calc_difference_kernel;
183         KernelFunctions<void(*)(float*, float*, int*, int, int)>                                 filter_nlm_blur_kernel;
184         KernelFunctions<void(*)(float*, float*, int*, int, int)>                                 filter_nlm_calc_weight_kernel;
185         KernelFunctions<void(*)(int, int, float*, float*, float*, float*, int*, int, int)>       filter_nlm_update_output_kernel;
186         KernelFunctions<void(*)(float*, float*, int*, int)>                                      filter_nlm_normalize_kernel;
187
188         KernelFunctions<void(*)(float*, int, int, int, float*, int*, int*, int, int, float)>                              filter_construct_transform_kernel;
189         KernelFunctions<void(*)(int, int, float*, float*, float*, int*, float*, float3*, int*, int*, int, int, int, int)> filter_nlm_construct_gramian_kernel;
190         KernelFunctions<void(*)(int, int, int, int, int, float*, int*, float*, float3*, int*, int)>                       filter_finalize_kernel;
191
192         KernelFunctions<void(*)(KernelGlobals *, ccl_constant KernelData*, ccl_global void*, int, ccl_global char*,
193                                ccl_global uint*, int, int, int, int, int, int, int, int, ccl_global int*, int,
194                                ccl_global char*, ccl_global unsigned int*, unsigned int, ccl_global float*)>        data_init_kernel;
195         unordered_map<string, KernelFunctions<void(*)(KernelGlobals*, KernelData*)> > split_kernels;
196
197 #define KERNEL_FUNCTIONS(name) \
198               KERNEL_NAME_EVAL(cpu, name), \
199               KERNEL_NAME_EVAL(cpu_sse2, name), \
200               KERNEL_NAME_EVAL(cpu_sse3, name), \
201               KERNEL_NAME_EVAL(cpu_sse41, name), \
202               KERNEL_NAME_EVAL(cpu_avx, name), \
203               KERNEL_NAME_EVAL(cpu_avx2, name)
204
205         CPUDevice(DeviceInfo& info, Stats &stats, bool background)
206         : Device(info, stats, background),
207 #define REGISTER_KERNEL(name) name ## _kernel(KERNEL_FUNCTIONS(name))
208           REGISTER_KERNEL(path_trace),
209           REGISTER_KERNEL(convert_to_half_float),
210           REGISTER_KERNEL(convert_to_byte),
211           REGISTER_KERNEL(shader),
212           REGISTER_KERNEL(filter_divide_shadow),
213           REGISTER_KERNEL(filter_get_feature),
214           REGISTER_KERNEL(filter_detect_outliers),
215           REGISTER_KERNEL(filter_combine_halves),
216           REGISTER_KERNEL(filter_nlm_calc_difference),
217           REGISTER_KERNEL(filter_nlm_blur),
218           REGISTER_KERNEL(filter_nlm_calc_weight),
219           REGISTER_KERNEL(filter_nlm_update_output),
220           REGISTER_KERNEL(filter_nlm_normalize),
221           REGISTER_KERNEL(filter_construct_transform),
222           REGISTER_KERNEL(filter_nlm_construct_gramian),
223           REGISTER_KERNEL(filter_finalize),
224           REGISTER_KERNEL(data_init)
225 #undef REGISTER_KERNEL
226         {
227
228 #ifdef WITH_OSL
229                 kernel_globals.osl = &osl_globals;
230 #endif
231                 use_split_kernel = DebugFlags().cpu.split_kernel;
232                 if(use_split_kernel) {
233                         VLOG(1) << "Will be using split kernel.";
234                 }
235
236 #define REGISTER_SPLIT_KERNEL(name) split_kernels[#name] = KernelFunctions<void(*)(KernelGlobals*, KernelData*)>(KERNEL_FUNCTIONS(name))
237                 REGISTER_SPLIT_KERNEL(path_init);
238                 REGISTER_SPLIT_KERNEL(scene_intersect);
239                 REGISTER_SPLIT_KERNEL(lamp_emission);
240                 REGISTER_SPLIT_KERNEL(do_volume);
241                 REGISTER_SPLIT_KERNEL(queue_enqueue);
242                 REGISTER_SPLIT_KERNEL(indirect_background);
243                 REGISTER_SPLIT_KERNEL(shader_setup);
244                 REGISTER_SPLIT_KERNEL(shader_sort);
245                 REGISTER_SPLIT_KERNEL(shader_eval);
246                 REGISTER_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao);
247                 REGISTER_SPLIT_KERNEL(subsurface_scatter);
248                 REGISTER_SPLIT_KERNEL(direct_lighting);
249                 REGISTER_SPLIT_KERNEL(shadow_blocked_ao);
250                 REGISTER_SPLIT_KERNEL(shadow_blocked_dl);
251                 REGISTER_SPLIT_KERNEL(enqueue_inactive);
252                 REGISTER_SPLIT_KERNEL(next_iteration_setup);
253                 REGISTER_SPLIT_KERNEL(indirect_subsurface);
254                 REGISTER_SPLIT_KERNEL(buffer_update);
255 #undef REGISTER_SPLIT_KERNEL
256 #undef KERNEL_FUNCTIONS
257         }
258
259         ~CPUDevice()
260         {
261                 task_pool.stop();
262         }
263
264         virtual bool show_samples() const
265         {
266                 return (TaskScheduler::num_threads() == 1);
267         }
268
269         void mem_alloc(const char *name, device_memory& mem, MemoryType /*type*/)
270         {
271                 if(name) {
272                         VLOG(1) << "Buffer allocate: " << name << ", "
273                                 << string_human_readable_number(mem.memory_size()) << " bytes. ("
274                                 << string_human_readable_size(mem.memory_size()) << ")";
275                 }
276
277                 mem.device_pointer = mem.data_pointer;
278
279                 if(!mem.device_pointer) {
280                         mem.device_pointer = (device_ptr)malloc(mem.memory_size());
281                 }
282
283                 mem.device_size = mem.memory_size();
284                 stats.mem_alloc(mem.device_size);
285         }
286
287         void mem_copy_to(device_memory& /*mem*/)
288         {
289                 /* no-op */
290         }
291
292         void mem_copy_from(device_memory& /*mem*/,
293                            int /*y*/, int /*w*/, int /*h*/,
294                            int /*elem*/)
295         {
296                 /* no-op */
297         }
298
299         void mem_zero(device_memory& mem)
300         {
301                 memset((void*)mem.device_pointer, 0, mem.memory_size());
302         }
303
304         void mem_free(device_memory& mem)
305         {
306                 if(mem.device_pointer) {
307                         if(!mem.data_pointer) {
308                                 free((void*)mem.device_pointer);
309                         }
310                         mem.device_pointer = 0;
311                         stats.mem_free(mem.device_size);
312                         mem.device_size = 0;
313                 }
314         }
315
316         virtual device_ptr mem_alloc_sub_ptr(device_memory& mem, int offset, int /*size*/, MemoryType /*type*/)
317         {
318                 return (device_ptr) (((char*) mem.device_pointer) + mem.memory_elements_size(offset));
319         }
320
321         void const_copy_to(const char *name, void *host, size_t size)
322         {
323                 kernel_const_copy(&kernel_globals, name, host, size);
324         }
325
326         void tex_alloc(const char *name,
327                        device_memory& mem,
328                        InterpolationType interpolation,
329                        ExtensionType extension)
330         {
331                 VLOG(1) << "Texture allocate: " << name << ", "
332                         << string_human_readable_number(mem.memory_size()) << " bytes. ("
333                         << string_human_readable_size(mem.memory_size()) << ")";
334                 kernel_tex_copy(&kernel_globals,
335                                 name,
336                                 mem.data_pointer,
337                                 mem.data_width,
338                                 mem.data_height,
339                                 mem.data_depth,
340                                 interpolation,
341                                 extension);
342                 mem.device_pointer = mem.data_pointer;
343                 mem.device_size = mem.memory_size();
344                 stats.mem_alloc(mem.device_size);
345         }
346
347         void tex_free(device_memory& mem)
348         {
349                 if(mem.device_pointer) {
350                         mem.device_pointer = 0;
351                         stats.mem_free(mem.device_size);
352                         mem.device_size = 0;
353                 }
354         }
355
356         void *osl_memory()
357         {
358 #ifdef WITH_OSL
359                 return &osl_globals;
360 #else
361                 return NULL;
362 #endif
363         }
364
365         void thread_run(DeviceTask *task)
366         {
367                 if(task->type == DeviceTask::RENDER) {
368                         thread_render(*task);
369                 }
370                 else if(task->type == DeviceTask::FILM_CONVERT)
371                         thread_film_convert(*task);
372                 else if(task->type == DeviceTask::SHADER)
373                         thread_shader(*task);
374         }
375
376         class CPUDeviceTask : public DeviceTask {
377         public:
378                 CPUDeviceTask(CPUDevice *device, DeviceTask& task)
379                 : DeviceTask(task)
380                 {
381                         run = function_bind(&CPUDevice::thread_run, device, this);
382                 }
383         };
384
385         bool denoising_set_tiles(device_ptr *buffers, DenoisingTask *task)
386         {
387                 mem_alloc("Denoising Tile Info", task->tiles_mem, MEM_READ_ONLY);
388
389                 TilesInfo *tiles = (TilesInfo*) task->tiles_mem.data_pointer;
390                 for(int i = 0; i < 9; i++) {
391                         tiles->buffers[i] = buffers[i];
392                 }
393
394                 return true;
395         }
396
397         bool denoising_non_local_means(device_ptr image_ptr, device_ptr guide_ptr, device_ptr variance_ptr, device_ptr out_ptr,
398                                        DenoisingTask *task)
399         {
400                 int4 rect = task->rect;
401                 int   r   = task->nlm_state.r;
402                 int   f   = task->nlm_state.f;
403                 float a   = task->nlm_state.a;
404                 float k_2 = task->nlm_state.k_2;
405
406                 int w = align_up(rect.z-rect.x, 4);
407                 int h = rect.w-rect.y;
408
409                 float *blurDifference = (float*) task->nlm_state.temporary_1_ptr;
410                 float *difference     = (float*) task->nlm_state.temporary_2_ptr;
411                 float *weightAccum    = (float*) task->nlm_state.temporary_3_ptr;
412
413                 memset(weightAccum, 0, sizeof(float)*w*h);
414                 memset((float*) out_ptr, 0, sizeof(float)*w*h);
415
416                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
417                         int dy = i / (2*r+1) - r;
418                         int dx = i % (2*r+1) - r;
419
420                         int local_rect[4] = {max(0, -dx), max(0, -dy), rect.z-rect.x - max(0, dx), rect.w-rect.y - max(0, dy)};
421                         filter_nlm_calc_difference_kernel()(dx, dy,
422                                                             (float*) guide_ptr,
423                                                             (float*) variance_ptr,
424                                                             difference,
425                                                             local_rect,
426                                                             w, 0,
427                                                             a, k_2);
428
429                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
430                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, w, f);
431                         filter_nlm_blur_kernel()       (difference, blurDifference, local_rect, w, f);
432
433                         filter_nlm_update_output_kernel()(dx, dy,
434                                                           blurDifference,
435                                                           (float*) image_ptr,
436                                                           (float*) out_ptr,
437                                                           weightAccum,
438                                                           local_rect,
439                                                           w, f);
440                 }
441
442                 int local_rect[4] = {0, 0, rect.z-rect.x, rect.w-rect.y};
443                 filter_nlm_normalize_kernel()((float*) out_ptr, weightAccum, local_rect, w);
444
445                 return true;
446         }
447
448         bool denoising_construct_transform(DenoisingTask *task)
449         {
450                 for(int y = 0; y < task->filter_area.w; y++) {
451                         for(int x = 0; x < task->filter_area.z; x++) {
452                                 filter_construct_transform_kernel()((float*) task->buffer.mem.device_pointer,
453                                                                     x + task->filter_area.x,
454                                                                     y + task->filter_area.y,
455                                                                     y*task->filter_area.z + x,
456                                                                     (float*) task->storage.transform.device_pointer,
457                                                                     (int*)   task->storage.rank.device_pointer,
458                                                                     &task->rect.x,
459                                                                     task->buffer.pass_stride,
460                                                                     task->radius,
461                                                                     task->pca_threshold);
462                         }
463                 }
464                 return true;
465         }
466
467         bool denoising_reconstruct(device_ptr color_ptr,
468                                    device_ptr color_variance_ptr,
469                                    device_ptr output_ptr,
470                                    DenoisingTask *task)
471         {
472                 mem_zero(task->storage.XtWX);
473                 mem_zero(task->storage.XtWY);
474
475                 float *difference     = (float*) task->reconstruction_state.temporary_1_ptr;
476                 float *blurDifference = (float*) task->reconstruction_state.temporary_2_ptr;
477
478                 int r = task->radius;
479                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
480                         int dy = i / (2*r+1) - r;
481                         int dx = i % (2*r+1) - r;
482
483                         int local_rect[4] = {max(0, -dx), max(0, -dy),
484                                              task->reconstruction_state.source_w - max(0, dx),
485                                              task->reconstruction_state.source_h - max(0, dy)};
486                         filter_nlm_calc_difference_kernel()(dx, dy,
487                                                             (float*) color_ptr,
488                                                             (float*) color_variance_ptr,
489                                                             difference,
490                                                             local_rect,
491                                                             task->buffer.w,
492                                                             task->buffer.pass_stride,
493                                                             1.0f,
494                                                             task->nlm_k_2);
495                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
496                         filter_nlm_calc_weight_kernel()(blurDifference, difference, local_rect, task->buffer.w, 4);
497                         filter_nlm_blur_kernel()(difference, blurDifference, local_rect, task->buffer.w, 4);
498                         filter_nlm_construct_gramian_kernel()(dx, dy,
499                                                               blurDifference,
500                                                               (float*)  task->buffer.mem.device_pointer,
501                                                               (float*)  task->storage.transform.device_pointer,
502                                                               (int*)    task->storage.rank.device_pointer,
503                                                               (float*)  task->storage.XtWX.device_pointer,
504                                                               (float3*) task->storage.XtWY.device_pointer,
505                                                               local_rect,
506                                                               &task->reconstruction_state.filter_rect.x,
507                                                               task->buffer.w,
508                                                               task->buffer.h,
509                                                               4,
510                                                               task->buffer.pass_stride);
511                 }
512                 for(int y = 0; y < task->filter_area.w; y++) {
513                         for(int x = 0; x < task->filter_area.z; x++) {
514                                 filter_finalize_kernel()(x,
515                                                          y,
516                                                          y*task->filter_area.z + x,
517                                                          task->buffer.w,
518                                                          task->buffer.h,
519                                                          (float*)  output_ptr,
520                                                          (int*)    task->storage.rank.device_pointer,
521                                                          (float*)  task->storage.XtWX.device_pointer,
522                                                          (float3*) task->storage.XtWY.device_pointer,
523                                                          &task->reconstruction_state.buffer_params.x,
524                                                          task->render_buffer.samples);
525                         }
526                 }
527                 return true;
528         }
529
530         bool denoising_combine_halves(device_ptr a_ptr, device_ptr b_ptr,
531                                       device_ptr mean_ptr, device_ptr variance_ptr,
532                                       int r, int4 rect, DenoisingTask * /*task*/)
533         {
534                 for(int y = rect.y; y < rect.w; y++) {
535                         for(int x = rect.x; x < rect.z; x++) {
536                                 filter_combine_halves_kernel()(x, y,
537                                                                (float*) mean_ptr,
538                                                                (float*) variance_ptr,
539                                                                (float*) a_ptr,
540                                                                (float*) b_ptr,
541                                                                &rect.x,
542                                                                r);
543                         }
544                 }
545                 return true;
546         }
547
548         bool denoising_divide_shadow(device_ptr a_ptr, device_ptr b_ptr,
549                                      device_ptr sample_variance_ptr, device_ptr sv_variance_ptr,
550                                      device_ptr buffer_variance_ptr, DenoisingTask *task)
551         {
552                 for(int y = task->rect.y; y < task->rect.w; y++) {
553                         for(int x = task->rect.x; x < task->rect.z; x++) {
554                                 filter_divide_shadow_kernel()(task->render_buffer.samples,
555                                                               task->tiles,
556                                                               x, y,
557                                                               (float*) a_ptr,
558                                                               (float*) b_ptr,
559                                                               (float*) sample_variance_ptr,
560                                                               (float*) sv_variance_ptr,
561                                                               (float*) buffer_variance_ptr,
562                                                               &task->rect.x,
563                                                               task->render_buffer.pass_stride,
564                                                               task->render_buffer.denoising_data_offset,
565                                                               use_split_kernel);
566                         }
567                 }
568                 return true;
569         }
570
571         bool denoising_get_feature(int mean_offset,
572                                    int variance_offset,
573                                    device_ptr mean_ptr,
574                                    device_ptr variance_ptr,
575                                    DenoisingTask *task)
576         {
577                 for(int y = task->rect.y; y < task->rect.w; y++) {
578                         for(int x = task->rect.x; x < task->rect.z; x++) {
579                                 filter_get_feature_kernel()(task->render_buffer.samples,
580                                                             task->tiles,
581                                                             mean_offset,
582                                                             variance_offset,
583                                                             x, y,
584                                                             (float*) mean_ptr,
585                                                             (float*) variance_ptr,
586                                                             &task->rect.x,
587                                                             task->render_buffer.pass_stride,
588                                                             task->render_buffer.denoising_data_offset,
589                                                             use_split_kernel);
590                         }
591                 }
592                 return true;
593         }
594
595         bool denoising_detect_outliers(device_ptr image_ptr,
596                                        device_ptr variance_ptr,
597                                        device_ptr depth_ptr,
598                                        device_ptr output_ptr,
599                                        DenoisingTask *task)
600         {
601                 for(int y = task->rect.y; y < task->rect.w; y++) {
602                         for(int x = task->rect.x; x < task->rect.z; x++) {
603                                 filter_detect_outliers_kernel()(x, y,
604                                                                 (float*) image_ptr,
605                                                                 (float*) variance_ptr,
606                                                                 (float*) depth_ptr,
607                                                                 (float*) output_ptr,
608                                                                 &task->rect.x,
609                                                                 task->buffer.pass_stride);
610                         }
611                 }
612                 return true;
613         }
614
615         void path_trace(DeviceTask &task, RenderTile &tile, KernelGlobals *kg)
616         {
617                 float *render_buffer = (float*)tile.buffer;
618                 uint *rng_state = (uint*)tile.rng_state;
619                 int start_sample = tile.start_sample;
620                 int end_sample = tile.start_sample + tile.num_samples;
621
622                 for(int sample = start_sample; sample < end_sample; sample++) {
623                         if(task.get_cancel() || task_pool.canceled()) {
624                                 if(task.need_finish_queue == false)
625                                         break;
626                         }
627
628                         for(int y = tile.y; y < tile.y + tile.h; y++) {
629                                 for(int x = tile.x; x < tile.x + tile.w; x++) {
630                                         path_trace_kernel()(kg, render_buffer, rng_state,
631                                                             sample, x, y, tile.offset, tile.stride);
632                                 }
633                         }
634
635                         tile.sample = sample + 1;
636
637                         task.update_progress(&tile, tile.w*tile.h);
638                 }
639         }
640
641         void denoise(DeviceTask &task, RenderTile &tile)
642         {
643                 tile.sample = tile.start_sample + tile.num_samples;
644
645                 DenoisingTask denoising(this);
646
647                 denoising.functions.construct_transform = function_bind(&CPUDevice::denoising_construct_transform, this, &denoising);
648                 denoising.functions.reconstruct = function_bind(&CPUDevice::denoising_reconstruct, this, _1, _2, _3, &denoising);
649                 denoising.functions.divide_shadow = function_bind(&CPUDevice::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
650                 denoising.functions.non_local_means = function_bind(&CPUDevice::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
651                 denoising.functions.combine_halves = function_bind(&CPUDevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
652                 denoising.functions.get_feature = function_bind(&CPUDevice::denoising_get_feature, this, _1, _2, _3, _4, &denoising);
653                 denoising.functions.detect_outliers = function_bind(&CPUDevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
654                 denoising.functions.set_tiles = function_bind(&CPUDevice::denoising_set_tiles, this, _1, &denoising);
655
656                 denoising.filter_area = make_int4(tile.x, tile.y, tile.w, tile.h);
657                 denoising.render_buffer.samples = tile.sample;
658
659                 RenderTile rtiles[9];
660                 rtiles[4] = tile;
661                 task.map_neighbor_tiles(rtiles, this);
662                 denoising.tiles_from_rendertiles(rtiles);
663
664                 denoising.init_from_devicetask(task);
665
666                 denoising.run_denoising();
667
668                 task.unmap_neighbor_tiles(rtiles, this);
669
670                 task.update_progress(&tile, tile.w*tile.h);
671         }
672
673         void thread_render(DeviceTask& task)
674         {
675                 if(task_pool.canceled()) {
676                         if(task.need_finish_queue == false)
677                                 return;
678                 }
679
680                 /* allocate buffer for kernel globals */
681                 device_only_memory<KernelGlobals> kgbuffer;
682                 kgbuffer.resize(1);
683                 mem_alloc("kernel_globals", kgbuffer, MEM_READ_WRITE);
684
685                 KernelGlobals *kg = new ((void*) kgbuffer.device_pointer) KernelGlobals(thread_kernel_globals_init());
686
687                 CPUSplitKernel *split_kernel = NULL;
688                 if(use_split_kernel) {
689                         split_kernel = new CPUSplitKernel(this);
690                         requested_features.max_closure = MAX_CLOSURE;
691                         if(!split_kernel->load_kernels(requested_features)) {
692                                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
693                                 mem_free(kgbuffer);
694
695                                 delete split_kernel;
696                                 return;
697                         }
698                 }
699
700                 RenderTile tile;
701                 while(task.acquire_tile(this, tile)) {
702                         if(tile.task == RenderTile::PATH_TRACE) {
703                                 if(use_split_kernel) {
704                                         device_memory data;
705                                         split_kernel->path_trace(&task, tile, kgbuffer, data);
706                                 }
707                                 else {
708                                         path_trace(task, tile, kg);
709                                 }
710                         }
711                         else if(tile.task == RenderTile::DENOISE) {
712                                 denoise(task, tile);
713                         }
714
715                         task.release_tile(tile);
716
717                         if(task_pool.canceled()) {
718                                 if(task.need_finish_queue == false)
719                                         break;
720                         }
721                 }
722
723                 thread_kernel_globals_free((KernelGlobals*)kgbuffer.device_pointer);
724                 kg->~KernelGlobals();
725                 mem_free(kgbuffer);
726                 delete split_kernel;
727         }
728
729         void thread_film_convert(DeviceTask& task)
730         {
731                 float sample_scale = 1.0f/(task.sample + 1);
732
733                 if(task.rgba_half) {
734                         for(int y = task.y; y < task.y + task.h; y++)
735                                 for(int x = task.x; x < task.x + task.w; x++)
736                                         convert_to_half_float_kernel()(&kernel_globals, (uchar4*)task.rgba_half, (float*)task.buffer,
737                                                                        sample_scale, x, y, task.offset, task.stride);
738                 }
739                 else {
740                         for(int y = task.y; y < task.y + task.h; y++)
741                                 for(int x = task.x; x < task.x + task.w; x++)
742                                         convert_to_byte_kernel()(&kernel_globals, (uchar4*)task.rgba_byte, (float*)task.buffer,
743                                                                  sample_scale, x, y, task.offset, task.stride);
744
745                 }
746         }
747
748         void thread_shader(DeviceTask& task)
749         {
750                 KernelGlobals kg = kernel_globals;
751
752 #ifdef WITH_OSL
753                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
754 #endif
755                 for(int sample = 0; sample < task.num_samples; sample++) {
756                         for(int x = task.shader_x; x < task.shader_x + task.shader_w; x++)
757                                 shader_kernel()(&kg,
758                                                 (uint4*)task.shader_input,
759                                                 (float4*)task.shader_output,
760                                                 (float*)task.shader_output_luma,
761                                                 task.shader_eval_type,
762                                                 task.shader_filter,
763                                                 x,
764                                                 task.offset,
765                                                 sample);
766
767                         if(task.get_cancel() || task_pool.canceled())
768                                 break;
769
770                         task.update_progress(NULL);
771
772                 }
773
774 #ifdef WITH_OSL
775                 OSLShader::thread_free(&kg);
776 #endif
777         }
778
779         int get_split_task_count(DeviceTask& task)
780         {
781                 if(task.type == DeviceTask::SHADER)
782                         return task.get_subtask_count(TaskScheduler::num_threads(), 256);
783                 else
784                         return task.get_subtask_count(TaskScheduler::num_threads());
785         }
786
787         void task_add(DeviceTask& task)
788         {
789                 /* split task into smaller ones */
790                 list<DeviceTask> tasks;
791
792                 if(task.type == DeviceTask::SHADER)
793                         task.split(tasks, TaskScheduler::num_threads(), 256);
794                 else
795                         task.split(tasks, TaskScheduler::num_threads());
796
797                 foreach(DeviceTask& task, tasks)
798                         task_pool.push(new CPUDeviceTask(this, task));
799         }
800
801         void task_wait()
802         {
803                 task_pool.wait_work();
804         }
805
806         void task_cancel()
807         {
808                 task_pool.cancel();
809         }
810
811 protected:
812         inline KernelGlobals thread_kernel_globals_init()
813         {
814                 KernelGlobals kg = kernel_globals;
815                 kg.transparent_shadow_intersections = NULL;
816                 const int decoupled_count = sizeof(kg.decoupled_volume_steps) /
817                                             sizeof(*kg.decoupled_volume_steps);
818                 for(int i = 0; i < decoupled_count; ++i) {
819                         kg.decoupled_volume_steps[i] = NULL;
820                 }
821                 kg.decoupled_volume_steps_index = 0;
822 #ifdef WITH_OSL
823                 OSLShader::thread_init(&kg, &kernel_globals, &osl_globals);
824 #endif
825                 return kg;
826         }
827
828         inline void thread_kernel_globals_free(KernelGlobals *kg)
829         {
830                 if(kg == NULL) {
831                         return;
832                 }
833
834                 if(kg->transparent_shadow_intersections != NULL) {
835                         free(kg->transparent_shadow_intersections);
836                 }
837                 const int decoupled_count = sizeof(kg->decoupled_volume_steps) /
838                                             sizeof(*kg->decoupled_volume_steps);
839                 for(int i = 0; i < decoupled_count; ++i) {
840                         if(kg->decoupled_volume_steps[i] != NULL) {
841                                 free(kg->decoupled_volume_steps[i]);
842                         }
843                 }
844 #ifdef WITH_OSL
845                 OSLShader::thread_free(kg);
846 #endif
847         }
848
849         virtual bool load_kernels(DeviceRequestedFeatures& requested_features_) {
850                 requested_features = requested_features_;
851
852                 return true;
853         }
854 };
855
856 /* split kernel */
857
858 class CPUSplitKernelFunction : public SplitKernelFunction {
859 public:
860         CPUDevice* device;
861         void (*func)(KernelGlobals *kg, KernelData *data);
862
863         CPUSplitKernelFunction(CPUDevice* device) : device(device), func(NULL) {}
864         ~CPUSplitKernelFunction() {}
865
866         virtual bool enqueue(const KernelDimensions& dim, device_memory& kernel_globals, device_memory& data)
867         {
868                 if(!func) {
869                         return false;
870                 }
871
872                 KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
873                 kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
874
875                 for(int y = 0; y < dim.global_size[1]; y++) {
876                         for(int x = 0; x < dim.global_size[0]; x++) {
877                                 kg->global_id = make_int2(x, y);
878
879                                 func(kg, (KernelData*)data.device_pointer);
880                         }
881                 }
882
883                 return true;
884         }
885 };
886
887 CPUSplitKernel::CPUSplitKernel(CPUDevice *device) : DeviceSplitKernel(device), device(device)
888 {
889 }
890
891 bool CPUSplitKernel::enqueue_split_kernel_data_init(const KernelDimensions& dim,
892                                                     RenderTile& rtile,
893                                                     int num_global_elements,
894                                                     device_memory& kernel_globals,
895                                                     device_memory& data,
896                                                     device_memory& split_data,
897                                                     device_memory& ray_state,
898                                                     device_memory& queue_index,
899                                                     device_memory& use_queues_flags,
900                                                     device_memory& work_pool_wgs)
901 {
902         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
903         kg->global_size = make_int2(dim.global_size[0], dim.global_size[1]);
904
905         for(int y = 0; y < dim.global_size[1]; y++) {
906                 for(int x = 0; x < dim.global_size[0]; x++) {
907                         kg->global_id = make_int2(x, y);
908
909                         device->data_init_kernel()((KernelGlobals*)kernel_globals.device_pointer,
910                                                    (KernelData*)data.device_pointer,
911                                                    (void*)split_data.device_pointer,
912                                                    num_global_elements,
913                                                    (char*)ray_state.device_pointer,
914                                                    (uint*)rtile.rng_state,
915                                                    rtile.start_sample,
916                                                    rtile.start_sample + rtile.num_samples,
917                                                    rtile.x,
918                                                    rtile.y,
919                                                    rtile.w,
920                                                    rtile.h,
921                                                    rtile.offset,
922                                                    rtile.stride,
923                                                    (int*)queue_index.device_pointer,
924                                                    dim.global_size[0] * dim.global_size[1],
925                                                    (char*)use_queues_flags.device_pointer,
926                                                    (uint*)work_pool_wgs.device_pointer,
927                                                    rtile.num_samples,
928                                                    (float*)rtile.buffer);
929                 }
930         }
931
932         return true;
933 }
934
935 SplitKernelFunction* CPUSplitKernel::get_split_kernel_function(string kernel_name, const DeviceRequestedFeatures&)
936 {
937         CPUSplitKernelFunction *kernel = new CPUSplitKernelFunction(device);
938
939         kernel->func = device->split_kernels[kernel_name]();
940         if(!kernel->func) {
941                 delete kernel;
942                 return NULL;
943         }
944
945         return kernel;
946 }
947
948 int2 CPUSplitKernel::split_kernel_local_size()
949 {
950         return make_int2(1, 1);
951 }
952
953 int2 CPUSplitKernel::split_kernel_global_size(device_memory& /*kg*/, device_memory& /*data*/, DeviceTask * /*task*/) {
954         return make_int2(1, 1);
955 }
956
957 uint64_t CPUSplitKernel::state_buffer_size(device_memory& kernel_globals, device_memory& /*data*/, size_t num_threads) {
958         KernelGlobals *kg = (KernelGlobals*)kernel_globals.device_pointer;
959
960         return split_data_buffer_size(kg, num_threads);
961 }
962
963 Device *device_cpu_create(DeviceInfo& info, Stats &stats, bool background)
964 {
965         return new CPUDevice(info, stats, background);
966 }
967
968 void device_cpu_info(vector<DeviceInfo>& devices)
969 {
970         DeviceInfo info;
971
972         info.type = DEVICE_CPU;
973         info.description = system_cpu_brand_string();
974         info.id = "CPU";
975         info.num = 0;
976         info.advanced_shading = true;
977         info.pack_images = false;
978
979         devices.insert(devices.begin(), info);
980 }
981
982 string device_cpu_capabilities(void)
983 {
984         string capabilities = "";
985         capabilities += system_cpu_support_sse2() ? "SSE2 " : "";
986         capabilities += system_cpu_support_sse3() ? "SSE3 " : "";
987         capabilities += system_cpu_support_sse41() ? "SSE41 " : "";
988         capabilities += system_cpu_support_avx() ? "AVX " : "";
989         capabilities += system_cpu_support_avx2() ? "AVX2" : "";
990         if(capabilities[capabilities.size() - 1] == ' ')
991                 capabilities.resize(capabilities.size() - 1);
992         return capabilities;
993 }
994
995 CCL_NAMESPACE_END